banhbaochay
banhbaochay

Reputation: 309

Difference between <% ... %> and <%= .. %> in rails 3

I have test method in helpers/application_helper.rb file:

def test
  concat("Hello world")
end

Then, in index.html.erb I call as:

Blah
<% test %>

The browser display:

Blah Hello world

It's normally, but if I change

<%= test %>

the browser display:

Blah Hello worldBlah Hello world

It duplicate all of page. I don't know why? What difference between them? Thanks for your help!

Upvotes: 7

Views: 3688

Answers (5)

Bala Karthik
Bala Karthik

Reputation: 1413

It is just like this

<% execute this code and display nothing %> 

and

<%= execute this code and display the result in the view %> 

Upvotes: 5

Aman Sharma
Aman Sharma

Reputation: 1

See this:

<%= You need to do this %>
<% You shouldn't do this %>

Upvotes: -1

Christopher Castiglione
Christopher Castiglione

Reputation: 1045

What's the Difference?

<% %> let's you evaluate the rails code in your view

<%= %> let's you evaluate the rails code in your view AND prints out a result on the page

Example #1: The equal sign is analogous to "puts" so:

<%= "Hello %> 

...is the same as:

<% puts "Hello" %> 

Example #2:

<% if !user_signed_in? %>
    <%= "This text shows up on the page" %>
<% end %> 

#returns "This text shows up on the page" if the user is signed in

Upvotes: 11

Dylan Markow
Dylan Markow

Reputation: 124419

From the Rails docs, concat is only supposed to be used within a <% %> code block. When you use it in a <%= %> code block, you see it twice because concat appends the provided text to the output buffer, but then it also returns the entire output buffer back to your helper method, which is then output by the <%=, causing your entire page to be duplicated.

Normally, you should not need to use concat much if at all (I've never come across a situation where I needed it). In your helper, you can just do this:

def test
  "Hello world"
end

And then use <%= test %> in your view.

Upvotes: 10

Michael Welburn
Michael Welburn

Reputation: 1075

Normally a <% %> is a snippet of Rails code (ie starting a conditional, ending a conditional, etc), whereas <%= %> actually evaluates an expression and returns a value to the page.

Upvotes: 16

Related Questions