The code below is working
-@items.each do |item|
%tr
%td
=item.quantity
times
%td= item.product.title
end
However I want to use { } instead of do ... end. Is it possible?
-@items.each { |item|
%tr
%td
=item.quantity
times
%td= item.product.title
}
For some reason it throws an exception. What did I do wrong?
In your working example the
endline is being treated as raw text, and will be included in your output. This works because you effectively don’t have anendkeyword. If you change this line to- end— i.e. add the hyphen (and make sure you’ve got your indentation correct) — you’ll see an error like:Note that Haml doesn’t always disallow
endkeywords, onlyendby itself. You can use them with statement modifiers, e.g.:or if you want to make use of the result of the block:
As for using
{}, you can’t. When Haml compiles the template to Ruby the hardcoded stringendis added to close any blocks as needed. It could be possible to modify Haml to be able to usedo..endor{}, but the extra complexity probably isn’t worth it. This way is a better fit with the common Ruby idiom of usingdo...endfor multiline blocks, and{}for single line ones.If you need to use
{}because of some issue with operator precedence it might be a sign to create a helper method. Your Haml templates (or templates in any language) aren’t the best place for complex logic, it’s best to move it into real Ruby files.