【发布时间】:2012-06-06 02:43:16
【问题描述】:
在 Rails 3.2 CaptureHelper 中,使用 capture 和 content_for 有什么区别,我为什么要选择其中一个?
【问题讨论】:
标签: ruby-on-rails
在 Rails 3.2 CaptureHelper 中,使用 capture 和 content_for 有什么区别,我为什么要选择其中一个?
【问题讨论】:
标签: ruby-on-rails
如果您查看 content_for 源,它会在内部调用 capture:
def content_for(name, content = nil, &block)
if content || block_given?
content = capture(&block) if block_given?
@view_flow.append(name, content) if content
nil
else
@view_flow.get(name)
end
end
因此,通过阅读该方法,看起来 content_for 的主要优点是它可以多次调用相同命名内容的多个块,并且每个额外的调用只会附加到已经呈现的任何内容上。而在捕获的情况下,如果您调用:
<% @greeting = capture do %>
Hello
<% end %>
然后再调用:
<% @greeting = capture do %>
Or, in espanol, Hola
<% end %>
那么最后一部分是唯一会被捕获的部分,'Hello' 将被丢弃。然而,在 content_for 中执行类似的操作将导致第二个调用附加到“Hello”。
【讨论】: