Reputation: 1260
Can somebody tell me what is the difference between the <%= %>
and <% %>
tags in erb? In which case should I use which one? What other tags can I use and what is their meaning?
Upvotes: 1
Views: 132
Reputation: 32130
As said
<% %>
will take the ruby code inside and evaluate it
<%= %>
will take the ruby code inside and evaluate it and print the result on the screen, which generally means will return a printable result which can be used in html as normal text
so doing
<div class="<% 'myclass' %>">
will result in
<div class="">
and <div class="<%= 'myclass' %>">
will result in
<div class="myclass">
you can see this railscast which explains it further http://railscasts.com/episodes/100-5-view-tips
Also, you will probably encounter this in the future and even forget I wrote this but it might be useful anyhow
in some cases, not every line of ruby code should be a line of <% %>. for example - using a case switch
this won't work:
<% case my_var %>
<% when 10 %>
<% some ruby code %>
<% end %>
but this will
<% case my_var
when 10 %>
<% some ruby code %>
<% end %>
so be wary of that
Upvotes: 6
Reputation: 3323
<% %>
Executes the ruby code within the brackets.
<%= %>
Prints something into erb file.
Upvotes: 1
Reputation: 755
<%= %>
is used when you want your executed ruby to be output to screen, that means anything written inside this block gets printed in your output screen,
where as <% %>
block is used to perform your ruby logic part, for eg your if
condition, loop
statement, etc..
Upvotes: 1