What is the difference between <%= … %> and <% … %> in Ruby on Rails

前端 未结 3 1819
难免孤独
难免孤独 2020-12-06 21:18

Does it have something to do with output?

So, <%= ...code... %> is used for outputting after code is executed, and <% ...code... %>

相关标签:
3条回答
  • 2020-12-06 21:39

    This is ERB templating markup (one of many templating languages supported by Rails). This markup:

    <% ... %>
    

    is used to evaluate a Ruby expression. Nothing is done with the result of that expression, however. By contrast, the markup:

    <%= ... %>
    

    does the same thing (runs whatever Ruby code is inside there) but it calls to_s on the result and replaces the markup with the resulting string.

    In short:

    <% just run code %>
    <%= run code and output the result %>
    

    For example:

    <% unless @items.empty? %>
      <ul>
        <% @items.each do |item| %>
          <li><%= item.name %></li>
        <% end %>
      </ul> 
    <% end %>
    

    In contrast, here's some Haml markup equivalent to the above:

    - unless @items.empty?
      %ul
        - @items.each do |item|
          %li= item.name
    
    0 讨论(0)
  • 2020-12-06 21:44

    Both execute the Ruby code contained within them. However, the different is in what they do with the returned value of the expression. <% ... %> will do nothing with the value. <%= ... %> will output the return value to whatever document it is executed in (typically a .erb or .rhtml document).

    Something to note, <%= ... %> will automatically escape any HTML contained in text. If you want to include any conditional HTML statements, do it outside the <% ... %>.

    <%= "<br />" if need_line_break %> <!-- Won't work -->
    
    <% if need_line_break %>
    <br />
    <% end %> <!-- Will work -->
    
    0 讨论(0)
  • 2020-12-06 22:01

    <%= is used to output the value of a single expression, e.g.

    <%= object.attribute %>
    <%= link_to 'Link Title', link_path %>
    

    while <% is used to execute arbitrary Ruby code.

    0 讨论(0)
提交回复
热议问题