4

I've noticed that in some lines of rails views, this is used:

<% # Code... -%> 

instead of:

<% # Code... %>

What is the difference?

Veger
  • 37,240
  • 11
  • 105
  • 116
HB.
  • 111
  • 1
  • 3

4 Answers4

17
    <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>. If the - was omitted, there would.

dylanfm
  • 6,292
  • 5
  • 28
  • 29
  • Yes. <% -%> suppresses new lines. It can be very useful when doing stuff in plain text (like emails) where that matters. – Luke Francl Nov 21 '08 at 21:16
8

The different options for evaluating code in ERB are as follows (they can be accessed in Textmate using Ctrl-Shift-. ):

  • <% %> 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 always adds a new line at the end of the string whereas print doesnt.

Basically, the -%> says don't output a new line at the end.

Chris Lloyd
  • 12,100
  • 7
  • 36
  • 32
2

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

<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

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

This is useful if you need to have a good looking code for HTML. Sometimes you'll find it useful when working sideby side with a designer

Hope this helps.

1

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.

Chu Yeow
  • 977
  • 1
  • 9
  • 16