Why many people use “-%>” instead of “%>” in Rails? [duplicate]

你离开我真会死。 提交于 2019-11-26 23:03:49

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/19789543/why-many-people-use-instead-of-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!