What's the difference between <% code %> and <%= code %> in Rails erb?

前端 未结 3 1023
天涯浪人
天涯浪人 2021-01-04 05:51

There seems to be a difference between the two, Though I can\'t tell what exactly.

<% code %>

And

<%= code %>
<         


        
相关标签:
3条回答
  • 2021-01-04 06:09

    <% %> will evaluate the ruby code contained

    <%= %> will evaluate and render the code contained

    So a template containing:

    Hello <% user.name %> how are you?
    

    ...would output:

    Hello  how are you
    

    ...whilst...

    Hello <%= user.name %> how are you?
    

    ...would output:

    Hello fred how are you
    

    <% %> is commonly used for iterators

    <ul>
      <% @users.each do |user| %>
        <li><%= user.name %></li>
      <% end %>
    </ul>
    
    0 讨论(0)
  • 2021-01-04 06:24

    <%= %> prints the return value of code statement into the browser and <% %> just executes the code.

    0 讨论(0)
  • 2021-01-04 06:31

    The <% and %> only evaluates the ruby code between them, while <%= and %> outputs the result of evaluation. Don't mix up though

    This will output "foo" to the access log and nil to the browser output

    <%= puts "foo" %>
    

    while

    <%= "foo" %>
    

    will output "foo" string to the browser.

    0 讨论(0)
提交回复
热议问题