Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 635
wlays Avatar asked Nov 30 '22 23:11

wlays


2 Answers

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
like image 143
Phrogz Avatar answered Dec 06 '22 16:12

Phrogz


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 -->
like image 30
Charles Caldwell Avatar answered Dec 06 '22 16:12

Charles Caldwell