Thursday, March 3, 2011

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?

From stackoverflow
  •     <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.

    Luke Francl : Yes. <% -%> suppresses new lines. It can be very useful when doing stuff in plain text (like emails) where that matters.
  • 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.

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

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

0 comments:

Post a Comment