简体   繁体   中英

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

Does it have something to do with output?

So, <%= ...code... %> is used for outputting after code is executed, and <% ...code... %> is only used for executing the code?

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

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

<%= is used to output the value of a single expression, eg

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

while <% is used to execute arbitrary Ruby code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM