开发者

Rails ERb best practices (<% %> vs <% -%> vs <%- -%>)

开发者 https://www.devze.com 2023-01-24 05:27 出处:网络
What is th开发者_JAVA技巧e recommended use of ERb in Rails when it comes to <% %> (evaluate Ruby code), <% -%> (evaluate Ruby code, suppress the trailing newline) and <%- -%> (evalua

What is th开发者_JAVA技巧e recommended use of ERb in Rails when it comes to <% %> (evaluate Ruby code), <% -%> (evaluate Ruby code, suppress the trailing newline) and <%- -%> (evaluate Ruby code, suppress the trailing newline and leading space)? It seems like <%- -%> would make the output HTML look nicest, but <% %> seems to be mostly what I see.


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.


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? :)


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
0

精彩评论

暂无评论...
验证码 换一张
取 消