Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between <% code %> and <%= code %> in Rails erb?

There seems to be a difference between the two, Though I can't tell what exactly.

<% code %>

And

<%= code %>
like image 567
Ariel Avatar asked Mar 19 '11 10:03

Ariel


People also ask

What does ERB mean in Ruby?

ERB (Embedded RuBy) is a feature of Ruby that enables you to conveniently generate any kind of text, in any quantity, from templates. The templates themselves combine plain text with Ruby code for variable substitution and flow control, which makes them easy to write and maintain.

How do ERB files work?

An ERB object works by building a chunk of Ruby code that will output the completed template when run. If safe_level is set to a non-nil value, ERB code will be run in a separate thread with $SAFE set to the provided level. eoutvar can be used to set the name of the variable ERB will build up its output in.

What is ERB template?

An ERB template looks like a plain-text document interspersed with tags containing Ruby code. When evaluated, this tagged code can modify text in the template. Puppet passes data to templates via special objects and variables, which you can use in the tagged Ruby code to control the templates' output.


2 Answers

<% %> will evaluate the ruby code contained

<%= %> will evaluate and render the code contained

So a template containing:

Hello <% user.name %> how are you?

...would output:

Hello  how are you

...whilst...

Hello <%= user.name %> how are you?

...would output:

Hello fred how are you

<% %> is commonly used for iterators

<ul>
  <% @users.each do |user| %>
    <li><%= user.name %></li>
  <% end %>
</ul>
like image 190
lebreeze Avatar answered Sep 18 '22 14:09

lebreeze


The <% and %> only evaluates the ruby code between them, while <%= and %> outputs the result of evaluation. Don't mix up though

This will output "foo" to the access log and nil to the browser output

<%= puts "foo" %>

while

<%= "foo" %>

will output "foo" string to the browser.

like image 42
Eimantas Avatar answered Sep 20 '22 14:09

Eimantas