[英]When do you use <% -%> instead of <% %>
I've noticed that in some lines of rails views, this is used: 我注意到在某些rails视图行中,使用了以下内容:
<% # Code... -%>
instead of: 代替:
<% # Code... %>
What is the difference? 有什么不同?
<ul>
<% @posts.each do |post| -%>
<li><%=post.title%></li>
<% end -%>
</ul>
There will be no new lines in between the <ul>
and first <li>
and the last closing </li>
and </ul>
. <ul>
和第一个<li>
以及最后一个结束</li>
和</ul>
之间不会有新的行。 If the - was omitted, there would. 如果 - 被省略,那就有了。
The different options for evaluating code in ERB are as follows (they can be accessed in Textmate using Ctrl-Shift-. ): 在ERB中评估代码的不同选项如下(可以使用Ctrl-Shift-在Textmate中访问它们):
<% %>
Just evaluate the contents. <% %>
只评估内容。 <%= %>
Evaluate the contents and puts the result. <%= %>
评估内容并放置结果。 <%= -%>
Evaluate the contents and prints the result. <%= -%>
评估内容并打印结果。 <%# %>
The contents is treated as a comment and not outputted. <%# %>
内容被视为注释而不输出。 Notice the difference between puts
and print
. 注意
puts
和print
之间的区别。 Puts always adds a new line at the end of the string whereas print doesnt. Puts总是在字符串的末尾添加一个新行,而print不是。
Basically, the -%>
says don't output a new line at the end. 基本上,
-%>
表示最后不输出新行。
Consider this 考虑一下
<div>
<% if @some_var == some_value %>
<p>Some message</p>
<% end %>
</div>
The code above yields to the HTML below if the @some_var is some_value 如果@some_var是some_value,则上面的代码会产生HTML
<div>
<p>Some message</p>
</div>
If you've put - in the closing tag, then the ERB interpreter would remove the new lines for those with code tag including - and result in the following 如果你把 - 在结束标记中,那么ERB解释器将删除包含代码标记的那些新行 - 并导致以下结果
<div>
<p>Some message</p>
</div>
This is useful if you need to have a good looking code for HTML. 如果您需要具有良好的HTML代码,这将非常有用。 Sometimes you'll find it useful when working sideby side with a designer
有时你会发现它在与设计师并肩工作时很有用
Hope this helps. 希望这可以帮助。
A little late, but I think it's worth pointing out that you can also do this: 有点晚了,但我认为值得指出你也可以这样做:
<%- @posts.each do |post| -%>
<li><%= post.title %></li>
<%- end %>
This strips away any whitespace in front. 这剥去了前面的任何空白。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.