Question

Sorry for this question, i think its more offtopic, but i couldn't find anything on google!

I saw now multiple times that a lot of people use -%> instead of just %>. Whats the sense?

Example:

<% @images.each_slice(6) do |slice| -%>
  <div class="gallery">
    <% slice.each do |image| -%>
      <%= image_tag(image.url, :alt => image.alt) %>
    <% end -%>
  </div>
<% end -%>

Source: Rails each loop insert tag every 6 items?

Here he has also used -%> for all blocks.

Was it helpful?

Solution

I would like to add some resources that I know about ERB :

  • Rails extends ERB, so that you can suppress the newline simply by adding a trailing hyphen to tags in Rails templates:

    <ul>
      <% for @item in @items -%>
        <li><%= @item %></li>
      <% end -%>
    </ul>
    
  • Comment markers use a hash sign:

     <%# This is just a comment %>
    
  • A tag with an equals sign indicates that enclosed code is an expression, and that the renderer should substitute the code element with the result of the code (as a string) when it renders the template. Use an expression to embed a line of code into the template, or to display the contents of a variable:

     Hello, <%= @name %>.
     Today is <%= Time.now.strftime('%A') %>.
    
  • With one equal sign the string will be encoded. To avoid encoding, you can use two equals signs (or raw):

        Hello, <%== @unencodedOutput %>
    
  • Tags without the equals sign denote that the enclosed code is a scriptlet. Each scriptlet is caught and executed, and the final result of the code is then injected in to the output at the point of the scriptlet.

    <ul>
      <% for @item in @shopping_list %>
        <li><%= @item %></li>
      <% end %>
    </ul>
    

    Scriptlets are most commonly used for embedding loops or conditional logic into templates:

Read An Introduction to ERB Templating to know more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top