What's the difference between <% code %

2019-02-12 02:04发布

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

<% code %>

And

<%= code %>

3条回答
萌系小妹纸
2楼-- · 2019-02-12 02:49

<% %> 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>
查看更多
▲ chillily
3楼-- · 2019-02-12 02:51

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.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-02-12 02:59

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

查看更多
登录 后发表回答