Rails html.erb filetype, difference between <% %> and <%= %>

ruby, ruby-on-rails

Solution

`<%=` outputs the result of the Ruby. `<%` just evaluates the Ruby.

<p>Hi! How are you? 1 + 1 = <%= 1 + 1 %></p>

Will become `<p>Hi! How are you? 1 + 1 = 2</p>`.

<p>Hi! How are you? 1 + 1 = <% 1 + 1 %></p>

Will become `<p>Hi! How are you? 1 + 1 = </p>`.

`<%` is generally used for flow control, ex. `if/else`. Example:

<% if model.nil? %>
  <%= render 'new_model_form' %>
<% else %>
  <%= render 'detail_view' %>
<% end %>

Read more at http://guides.rubyonrails.org/layouts_and_rendering.html

Problem

I just began digging into Ruby and Ruby on Rails, and I noticed two options for embedding Ruby syntax within .html.erb files: ``` <% #ruby code here %> ``` Or: ``` <%= #ruby code here %> ``` How should I choose one over the other?

Original source

Related problems