Rails ERb 最佳实践(<% %> 与 <% -%> 与 <%- -%>)
当涉及 <% %>
(评估 Ruby 代码)、<% -%>
(评估 Ruby 代码)时,Rails 中 ERb 的推荐用途是什么,抑制尾随换行符)和 <%- -%>
(评估 Ruby 代码,抑制尾随换行符和前导空格)?看起来 <%- -%>
会使输出 HTML 看起来最好,但 <% %>
似乎主要是我所看到的。
What is the 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是个人喜好。我用 <% %>当我编写循环或块时,因为我想要在那里添加新行。我使用 <% -%>在极少数情况下进行变量赋值。而且我从不使用 <%- -%>因为这样的选择太多了。
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.
我刚刚阅读 http://ruby-doc.org/ruby-1.9/classes /ERB.html ,您甚至可以使用单个百分号表示单行(如果该行上没有其他内容)
文档中的示例:
aaa 几乎像 HAML,不是吗? :)
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:
aaaalmost like HAML, isn't it? :)
我认为尾随连字符
-%>
不再有效;我刚刚尝试在 Ruby 2.6.6 中使用它时遇到错误。但是,@onetom 建议对整行代码仅使用百分比%
,它不会输出任何内容,并且不会在末尾保留不需要的换行符。示例:
尾随连字符
错误消息:
无尾随连字符:
输出:
仅百分比:
输出:
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
Error message:
No trailing hyphen:
Output:
Percent only:
Output: