gpt4 book ai didi

ruby-on-rails - ruby rails : provide vs content_for

转载 作者:数据小太阳 更新时间:2023-10-29 06:27:19 27 4
gpt4 key购买 nike

我今天遇到了 View 辅助函数“provide”。通过查看它的手册,我仍然对它与“content_for”的不同之处感到困惑。

provide(name, content = nil, &block)

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:这对我来说很抽象 - 任何人都可以通过给出一个说明性示例来充实它吗?

问题 2:使用 asset pipeline,哪个性能更好,为什么?

谢谢!

最佳答案

首先,什么是流媒体?为什么要使用它?

流式处理是自上而下(由外向内)呈现页面的替代方法。默认的渲染行为是从里到外。必须在您的 Controller 中启用流式传输:

class MyController
def action
render stream: true # Streaming enabled
end
end

根据documentation :

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 来定义多个内容 block 。这样做会连接 block 并将其传递给布局:

# 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 调用的 block 将被发送到模板:

# 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 - ruby rails : provide vs content_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27814500/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com