使用 `capture` 和 `concat` 比直接在 Rails 中渲染块有什么好处
What is the benefit of using `capture` and `concat` than just rendering a block directly in Rails
查看 docs for concat
,有人在下面给出了如何使用它的示例:
def block_to_partial(partial_name, options = {}, &block)
options.merge!(:body => capture(&block))
concat(render(:partial => partial_name, :locals => options), block.binding)
end
但是如果没有 concat
就不能这样做吗?它可以与 render
一起使用,对吗?
render
仅呈现一个模板 - concat 将其写入响应中使用的输出缓冲区。
以本次ERB为例:
<% render partial: 'foo/bar' %>
由于我们使用 <% %>
Ruby 代码的输出只是被评估。实际上没有任何输出。
<%= render partial: 'foo/bar' %>
和
<% concat(render(partial: 'foo/bar')) %>
都会将部分内容添加到响应正文中。
使用 concat
的真正好处是当您创建应直接写入缓冲区的辅助方法时。
另一方面,capture
用于将块(HTML 的块)的输出保存到变量,以便它可以在视图中的其他地方使用。
查看 docs for concat
,有人在下面给出了如何使用它的示例:
def block_to_partial(partial_name, options = {}, &block)
options.merge!(:body => capture(&block))
concat(render(:partial => partial_name, :locals => options), block.binding)
end
但是如果没有 concat
就不能这样做吗?它可以与 render
一起使用,对吗?
render
仅呈现一个模板 - concat 将其写入响应中使用的输出缓冲区。
以本次ERB为例:
<% render partial: 'foo/bar' %>
由于我们使用 <% %>
Ruby 代码的输出只是被评估。实际上没有任何输出。
<%= render partial: 'foo/bar' %>
和
<% concat(render(partial: 'foo/bar')) %>
都会将部分内容添加到响应正文中。
使用 concat
的真正好处是当您创建应直接写入缓冲区的辅助方法时。
capture
用于将块(HTML 的块)的输出保存到变量,以便它可以在视图中的其他地方使用。