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

前端 未结 3 1022
天涯浪人
天涯浪人 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

      <% @users.each do |user| %>
    • <%= user.name %>
    • <% end %>

提交回复
热议问题