August 18, 2016

Should I use <% or <%=

When writing your views in Ruby on Rails using ERB templates there will be times when you want to put some Ruby code in there to achieve what you are trying to do. When you are doing this though, when should you use <% %> and when should you use <%= %> ??

To make this decision, you just need to know if you want to display the result of the Ruby code on your page or not. If you do use <%= %>, it will show what the piece of ruby code equals, if you don't, then you use <% %> and it will just run the code but not display it.

For example the following code

<% @customers.each do |customer| %>
  <p><%= customer.name %></p>
<% end %>

Would loop through each of your customers that you, but only display the names:

George
Mavis