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

只谈情不闲聊 提交于 2019-11-27 21:31:30

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.

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