HB.
HB.

Reputation: 111

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

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

<% # Code... -%> 

instead of:

<% # Code... %>

What is the difference?

Upvotes: 4

Views: 462

Answers (4)

Chu Yeow
Chu Yeow

Reputation: 977

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.

Upvotes: 1

Chris Lloyd
Chris Lloyd

Reputation: 12318

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.

Upvotes: 8

NetMustang
NetMustang

Reputation:

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.

Upvotes: 2

dylanfm
dylanfm

Reputation: 6345

    <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.

Upvotes: 17

Related Questions