Rails ERb best practices (<% %> vs <% -%> vs <%- -%>)
I don't think the trailing hyphen -%>
works any more; I just got an error trying to use it in Ruby 2.6.6. However, @onetom's suggestion of using just a percent %
for an entire line of code works, it outputs nothing, and doesn't keep the unwanted newline at the end.
Examples:
Trailing hyphen
line1
<%- sought = 'pattern' -%>
line3
Error message:
file.erb:1: syntax error, unexpected ';' (SyntaxError)
; - sought = 'pattern' -; _erbout.<< "\n".freeze
No trailing hyphen:
line1
<%- sought = 'pattern' %>
line3
Output:
line1
line3
Percent only:
line1
% sought = 'pattern'
line3
Output:
line1
line3
I just read in http://ruby-doc.org/ruby-1.9/classes/ERB.html that you can even use a single percent sign for oneliners (if there is nothing else on that line)
Example from the docs:
<%# ignore numerous minor requests -- focus on priorities %>
% priorities.each do |priority|
* <%= priority %>
% end
aaaalmost like HAML, isn't it? :)
It's a personal preference. I use <% %> when I'm writing a loop or a block, because I want new lines there. I use <% -%> in rare cases of variable assignment. And I never use <%- -%> because that's one option too many.