When you use <% -%> instead of <%%>

I noticed that in some lines of rail views this is used:

 <% # Code... -%> 

instead:

 <% # Code... %> 

What is the difference?

+4
source share
4 answers
  <ul> <% @posts.each do |post| -%> <li><%=post.title%></li> <% end -%> </ul> 

There will be no new lines between <ul> and the first <li> and last closing </li> and </ul> . If - is omitted, then it will be.

+17
source

The various options for evaluating code in ERB are as follows (you can access them in Textmate using Ctrl-Shift-.):

  • <% %> Just rate the content.
  • <%= %> Rate the content and put the result.
  • <%= -%> Rate the contents and print the result.
  • <%# %> Content is treated as a comment and is not displayed.

Note the difference between puts and print . The supply always adds a new line at the end of the line, while printing does not.

Basically, -%> says that a new line is not output at the end.

+8
source

Consider this

 <div> <% if @some_var == some_value %> <p>Some message</p> <% end %> </div> 

The above code outputs to the HTML below if @some_var is some_value

 <div> <p>Some message</p> </div> 

If you put in the closing tag, then the ERB interpreter will delete new lines for those who have a code tag, including

 <div> <p>Some message</p> </div> 

This is useful if you need good HTML code. Sometimes you find it useful when working side by side with a designer.

Hope this helps.

+2
source

A bit late, but I think it's worth noting that you can do this too:

 <%- @posts.each do |post| -%> <li><%= post.title %></li> <%- end %> 

This casts blanks ahead.

+1
source

All Articles