<%= ... %> 和有什么区别?和<%...%>在 Ruby on Rails 中 [英] What is the difference between <%= ... %> and <% ... %> in Ruby on Rails

查看:54
本文介绍了<%= ... %> 和有什么区别?和<%...%>在 Ruby on Rails 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

和输出有关系吗?

所以,<%= ...code... %> 用于代码执行后的输出,<% ...code... %> 只用于执行代码?

So, <%= ...code... %> is used for outputting after code is executed, and <% ...code... %> is only used for executing the code?

推荐答案

这是ERB 模板标记(Rails 支持的众多模板语言之一).此标记:

This is ERB templating markup (one of many templating languages supported by Rails). This markup:

<% ... %>

用于评估 Ruby 表达式.但是,该表达式的结果没有任何处理.相比之下,标记:

is used to evaluate a Ruby expression. Nothing is done with the result of that expression, however. By contrast, the markup:

<%= ... %>

做同样的事情(运行里面的任何 Ruby 代码)但它对结果调用 to_s用结果字符串替换标记.

does the same thing (runs whatever Ruby code is inside there) but it calls to_s on the result and replaces the markup with the resulting string.

简而言之:

<% just run code %>
<%= run code and output the result %>

例如:

<% unless @items.empty? %>
  <ul>
    <% @items.each do |item| %>
      <li><%= item.name %></li>
    <% end %>
  </ul> 
<% end %>

相比之下,这里有一些与上面等效的 Haml 标记:

- unless @items.empty?
  %ul
    - @items.each do |item|
      %li= item.name

这篇关于&lt;%= ... %&gt; 和有什么区别?和&lt;%...%&gt;在 Ruby on Rails 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆