11

Longshot, but I'm wondering if there's any way to do something like this:

%p # ONLY SHOW THIS IF LOCAL VARIABLE show_paras IS TRUE
  = name

In other words, it always shows the content inside, but it only wraps a container around it if (some-condition) is true.

mahemoff
  • 44,526
  • 36
  • 160
  • 222
  • 1
    This is a duplicate of: http://stackoverflow.com/questions/7237308/how-can-i-conditionally-wrap-some-haml-content-in-a-tag – David J. Jun 16 '12 at 21:14

4 Answers4

16

You could use raw html, but then you'd have to have the if statement both at the beginning and end:

- if show_paras
  <p>
= name
- if show_paras
  </p>

Assuming you're doing more than just = name, you could use a partial:

- if show_paras
  %p= render "my_partial"
- else
  = render "my_partial"

You could also use HAML's surround (though this is a little messy):

- surround(show_paras ? "<p>" : "", show_paras ? "</p>" : "") do
  = name

Finally, what I would probably do is not try to omit the p tag at all, and just use CSS classes to set up two different p styles to look the way I want:

%p{:class => show_paras ? "with_paras" : "without_paras"}
  = name
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
  • Thanks, surround is the kind of thing I was looking for. Little messy as you say, but you could make it very clean with a helper function building on surround. Thanks! – mahemoff Dec 26 '11 at 17:19
4

Another option is to wrap it in an alternative tag if the condition isn't met, using haml_tag:

- haml_tag(show_paras ? :p : :div) do
  = name
Jamie Schembri
  • 6,047
  • 4
  • 25
  • 37
2
- haml_tag_if show_paras, :p do
  = name

https://github.com/haml/haml/commit/66a8ee080a9fb82907618227e88ce5c2c969e9d1

Richard Peck
  • 76,116
  • 9
  • 93
  • 147
  • The old haml_tag_if! Nice. – mahemoff Nov 30 '16 at 14:12
  • what if I want to add atrributes to the container, such as an href to a link? Documentation did not enlighten me :/ https://haml.info/docs/yardoc/Haml/Helpers.html#haml_tag_if-instance_method – xeruf Sep 15 '22 at 11:17
2

The cleanest way I can think of doing is like this:

= show_paras ? content_tag(:p, name) : name

But it's not exactly haml.

Generally markup is the for the content, so if show_paras is a more presentational tweak you should probably be using css to change the behaviour of the %p instead

Andrew Nesbitt
  • 5,976
  • 1
  • 32
  • 36
  • True, I take your point, but in my case, it's a bit more involved as there's conditional content inside which would make it arguably a para (or section etc) in some cases, but in other cases, just a simple div/span. – mahemoff Dec 26 '11 at 17:20