<%...%>之间的差异并且<%=..%>在轨道 3 [英] Difference between <% ... %> and <%= .. %> in rails 3

查看:55
本文介绍了<%...%>之间的差异并且<%=..%>在轨道 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have test method in helpers/application_helper.rb file:

def test
  concat("Hello world")
end

然后,在 index.html.erb 中我称之为:

Then, in index.html.erb I call as:

Blah
<% test %>

浏览器显示:

废话世界你好

这是正常的,但如果我改变了

It's normally, but if I change

<%= test %>

浏览器显示:

废话你好世界废话你好世界

Blah Hello worldBlah Hello world

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

It duplicate all of page. I don't know why? What difference between them? Thanks for your help!

推荐答案

来自 Rails 文档concat 只能在 <% %> 代码块中使用.当您在 <%= %> 代码块中使用它时,您会看到它两次,因为 concat 将提供的文本附加到输出缓冲区,但随后它也会返回整个输出缓冲区返回到您的辅助方法,然后由 <%= 输出,从而导致整个页面被复制.

From the Rails docs, concat is only supposed to be used within a <% %> code block. When you use it in a <%= %> code block, you see it twice because concat appends the provided text to the output buffer, but then it also returns the entire output buffer back to your helper method, which is then output by the <%=, causing your entire page to be duplicated.

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

Normally, you should not need to use concat much if at all (I've never come across a situation where I needed it). In your helper, you can just do this:

def test
  "Hello world"
end

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

And then use <%= test %> in your view.

这篇关于&lt;%...%&gt;之间的差异并且&lt;%=..%&gt;在轨道 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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