rails 3中<%...%>和<%= ..%>之间的差异

ban*_*hay 6 ruby-on-rails

我在helpers/application_helper.rb文件中有测试方法:

def test
  concat("Hello world")
end
Run Code Online (Sandbox Code Playgroud)

然后,在index.html.erb中我调用:

Blah
<% test %>
Run Code Online (Sandbox Code Playgroud)

浏览器显示:

布拉赫你好世界

这通常是,但如果我改变

<%= test %>
Run Code Online (Sandbox Code Playgroud)

浏览器显示:

Blah你好worldBlah你好世界

它复制了所有页面.我不知道为什么?他们之间有什么区别?谢谢你的帮助!

小智 14

通常,<%%>是Rails代码的片段(即启动条件,结束条件等),而<%=%>实际上计算表达式并向页面返回值.


Chr*_*one 11

有什么不同?

<% %> 让我们评估视图中的rails代码

<%= %> 让我们评估视图中的rails代码并在页面上打印出结果

示例#1: 等号类似于"puts"所以:

<%= "Hello %> 
Run Code Online (Sandbox Code Playgroud)

...是相同的:

<% puts "Hello" %> 
Run Code Online (Sandbox Code Playgroud)

示例#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
Run Code Online (Sandbox Code Playgroud)


Dyl*_*kow 10

Rails文档中,concat只应该在<% %>代码块中使用.当你在<%= %>代码块中使用它时,你会看到它两次,因为它将concat提供的文本附加到输出缓冲区,但是它也会将整个输出缓冲区返回给你的帮助器方法,然后由<%=你输出,导致你的整个页面被复制.

通常情况下,你根本不需要使用concat太多(我从来没有遇到过我需要它的情况).在你的助手中,你可以这样做:

def test
  "Hello world"
end
Run Code Online (Sandbox Code Playgroud)

然后<%= test %>在您的视图中使用.


Bal*_*hik 5

就是这样

<% execute this code and display nothing %> 
Run Code Online (Sandbox Code Playgroud)

<%= execute this code and display the result in the view %> 
Run Code Online (Sandbox Code Playgroud)