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

Comments?

I've changed how I run my blog now and have decided to not integrate comments into this new version. I am happy to answer any questions though, feel free to send me an email through the link at the top of the screen. Happy Programming.