Ruby on Rails:提供与 content_for

Ruby on Rails: provide vs content_for

我今天遇到了视图辅助函数 "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,哪个性能更好,为什么?

谢谢!

很想知道有什么不同,当 Thong Kuah 指向 api 时,答案里面:

This means that, if you have yield :title in your layout and you want to use streaming, you would have to render the whole template (and eventually trigger all queries) before streaming the title and all assets, which kills the purpose of streaming. For this reason Rails 3.1 introduces a new helper called provide that does the same as content_for but tells the layout to stop searching for other entries and continue rendering.

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

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

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

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

# 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>