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

前端 未结 5 639
别那么骄傲
别那么骄傲 2020-12-09 13:59

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

def test
  concat(\"Hello world\")
end

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

相关标签:
5条回答
  • 2020-12-09 14:13

    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.

    0 讨论(0)
  • 2020-12-09 14:21

    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
    
    0 讨论(0)
  • 2020-12-09 14:25

    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.

    0 讨论(0)
  • 2020-12-09 14:27

    See this:

    <%= You need to do this %>
    <% You shouldn't do this %>
    
    0 讨论(0)
  • 2020-12-09 14:38

    It is just like this

    <% execute this code and display nothing %> 
    

    and

    <%= execute this code and display the result in the view %> 
    
    0 讨论(0)
提交回复
热议问题