2
votes

in ruby you can do conditional block like so

block do |n|
  puts n
end if foo == bar

which would translate into erb as

<% block do |n| %>
  <%= n %>
<% end if foo == bar %>

is there a way to achieve this in haml other than wrapping the block in a condition?

2
You could do that in Ruby, but you would be using, in my opinion, and in the opinion of many others, bad style: see GitHub's Ruby style guide which says to avoid do end chaining. - David J.
Even if I was to say "ok, the do ... end.if style is readable" (it is not), I cringe to see it done in Haml. I'll give some alternatives in the answers below. - David J.

2 Answers

7
votes
- block do |n|
  = n
- end if foo == bar

Haml does allow end in this circumstance.

0
votes

Please put the if up front -- it makes it more readable:

- if foo == bar
  - block do |n|
    = n

And, if this occurs frequently, consider writing a custom Haml helper.

(I mentioned the GitHub Ruby Style guide above in a comment. If you search Google for 'ruby do end chaining' you'll see many style guides that recommend using that construct.)