I have test method in helpers/application_helper.rb file:
def test
concat(\"Hello world\")
end
Then, in index.html.erb I call as:
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.
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
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.
See this:
<%= You need to do this %>
<% You shouldn't do this %>
It is just like this
<% execute this code and display nothing %>
and
<%= execute this code and display the result in the view %>