rails 3中和之间的差异

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

def test concat("Hello world") end 

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

 Blah  

浏览器显示:

Blah你好世界

这通常是,但如果我改变

  

浏览器显示:

Blah Hello worldBlah你好世界

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

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

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

 def test "Hello world" end 

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

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

有什么不同?

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

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

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

 <%= "Hello %> 

…是相同的:

 <% puts "Hello" %> 

示例#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 

就是这样

 <% execute this code and display nothing %> 

 <%= execute this code and display the result in the view %> 

看到这个:

 <%= You need to do this %> <% You shouldn't do this %>