The difference between <% ...%> and <% = ..%> in rails 3

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

 def test concat("Hello world") end 

Then in index.html.erb I call:

 Blah <% test %> 

Browser display:

Blah hello world

Usually, but if I change

 <%= test %> 

browser display:

Blah hello world

It duplicates the entire page. I do not know why? What is the difference between the two? Thanks for your help!

+6
source share
5 answers

From the Rails concat , concat supposed to be used only in the <% %> concat <% %> code block. When you use it in a code block <%= %> , you see it twice because concat adds 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 using <%= , which will lead to duplication of the entire page.

Usually you don’t need to use concat lot, if at all (I never came across a situation where I needed it). In your assistant you can simply do this:

 def test "Hello world" end 

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

+10
source

Typically, <%%> is a piece of Rails code (i.e., starting a conditional expression, terminating a conditional, etc.), while <% =%> actually evaluates the expression and returns the value to the page.

+13
source

What's the difference?

<% %> allows you to evaluate the rail code in your view

<%= %> allows you to evaluate the rail code in your view and displays the result on the page

Example # 1: The equal sign is the same as the "puts" value:

 <%= "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 
+9
source

This is just

 <% execute this code and display nothing %> 

and

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

See this:

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

Source: https://habr.com/ru/post/906811/


All Articles