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 -->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With