wlays
wlays

Reputation: 307

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?

Upvotes: 5

Views: 8603

Answers (3)

Phrogz
Phrogz

Reputation: 303549

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

Upvotes: 12

Charles Caldwell
Charles Caldwell

Reputation: 17189

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

Upvotes: 4

jackwanders
jackwanders

Reputation: 16050

<%= 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.

Upvotes: 3

Related Questions