Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 286
banhbaochay Avatar asked Jan 25 '12 03:01

banhbaochay


2 Answers

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.

like image 151
Michael Welburn Avatar answered Sep 25 '22 06:09

Michael Welburn


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
like image 27
Christopher Castiglione Avatar answered Sep 25 '22 06:09

Christopher Castiglione