0

Sorry I'm very new to Ruby and this is probably a simple question and I am just searching wrong for it. For example:

<% flash.each do |key, value| %>
<%= content_tag :div, value, class: "alert alert-#{key}" %>
<% end %>

Why do we only use <% %> at the beginning and end of the loop, but <%= is used in the loop?

Another example, no loop involved:

<li><%= link_to "Contact Us", new_contact_path %></li>

Why am I using <%= instead of <% here? Thanks for helping me with this newb question

Ryan Smith
  • 98
  • 1
  • 9

2 Answers2

1

You'll use <%= when you want the ERB to actually render code as a string in the browser, and <% when you simply want to execute Ruby code (e.g. performing an iteration, setting a variable, etc.)

In your examples:

<% flash.each do |key, value| %>
<%= content_tag :div, value, class: "alert alert-#{key}" %>
<% end %>

<% is used on flash.each to iterate over the flash variable, and then <%= is used to actually render a content_tag containing the values set when piping in key and value into the block.

CDub
  • 13,146
  • 4
  • 51
  • 68
0

Are you using erb?

<%> will execute the ruby code inside the brackets

<%=> will actually render some code in your view

Scott
  • 422
  • 1
  • 4
  • 17