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\".
prov
First of all, what is streaming? Why would you use it?
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
According to the 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.
So, if you're not using streaming, is there still a difference?
Yes.
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
<%= yield :surprise %>
<%= yield %>
But it's not very interesting...
# template.html.erb
<%= content_for :surprise, "Hello" %>
I've got your content!
<%= content_for :surprise, ", World!" %>
# Generated HTML
Hello, World!
I've got your content!
But it's not very interesting...
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
<%= yield :title %>
# template.html.erb
<%= provide :title, "Foo" %>
<%= provide :title, "bar" %>
# Generated HTML
Foo