Ruby on Rails:提供vs content_for [英] Ruby on Rails: provide vs content_for
问题描述
我今天遇到了提供"视图助手功能.通过查看其手册,我仍然对它与"content_for"的区别感到困惑.
I came across the view helper function "provide" today. By looking into its manual I am still confused on how it is different from "content_for".
提供(名称,内容=无,& block)
provide(name, content = nil, &block)
与content_for相同,但与流式传输一起使用时会直接刷新 回到布局.换句话说,如果您要串联多个 渲染给定模板时,将其复制到相同的缓冲区,您应该 使用content_for,如果不使用,则使用Provide告知布局停止 寻找更多内容.
The same as content_for but when used with streaming flushes straight back to the layout. In other words, if you want to concatenate several times to the same buffer when rendering a given template, you should use content_for, if not, use provide to tell the layout to stop looking for more contents.
问题1:对我来说,这很抽象-有人可以举一个示范性的例子来充实它吗?
Question 1: this is quite abstract to me - could anyone flesh it out by giving a demonstrative example?
问题2:使用资产管道,效果更好,为什么呢?
Question 2: working with asset pipeline, which performs better and why?
谢谢!
推荐答案
首先,什么是流媒体?您为什么要使用它?
流式传输是自上而下(从里到外)呈现页面的另一种方法.默认渲染行为是由内而外的.必须在您的控制器中启用流式传输:
Streaming is alternate method of rendering pages top-down (outside-in). The default rendering behavior is inside-out. Streaming must be enabled in your controller:
class MyController
def action
render stream: true # Streaming enabled
end
end
根据文档:
对于轻量级动作,流媒体可能被认为是过大的 如新建或修改.流媒体的真正好处在于价格昂贵 例如,对数据库执行大量查询的操作.
Streaming may be considered to be overkill for lightweight actions like new or edit. The real benefit of streaming is on expensive actions that, for example, do a lot of queries on the database.
因此,如果您不使用流式传输,还有区别吗?
是的
区别在于模板可以通过多次调用content_for
来定义多个内容块.这样做将串联块并将其传递到布局:
The difference is a template can define multiple content blocks by calling content_for
multiple times. Doing so will concatenate the blocks and pass that to the layout:
# layout.html.erb
<div class="heading"><%= yield :surprise %></div>
<div class="body">
<p><%= yield %></p>
<p>But it's not very interesting...</p>
</div>
# template.html.erb
<%= content_for :surprise, "Hello" %>
I've got your content!
<%= content_for :surprise, ", World!" %>
# Generated HTML
<div class="heading">Hello, World!</div>
<div class="body">
<p>I've got your content!</p>
<p>But it's not very interesting...</p>
</div>
由于provide
不再继续搜索所提供的模板,因此只有传递给第一个provide
调用的块将被发送到模板:
Since provide
doesn't continue searching the provided template, only the block passed to the first provide
call will be sent to the template:
# layout.html.erb
<div class="heading"><%= yield :title %></div>
# template.html.erb
<%= provide :title, "Foo" %>
<%= provide :title, "bar" %>
# Generated HTML
<div class="heading">Foo</div>
这篇关于Ruby on Rails:提供vs content_for的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!