Dmitri
Dmitri

Reputation: 2457

Rails yield and content_for in partial

I've got used to use content_for and yield for my views in order to set the page title and other neat stuff, related to view rendering.

And now I got stuck with next scheme: LAYOUT -> VIEW (edit.html.erb) -> PARTIAL (_main.html). That is - view contains a partial.

If I define content_for :view_content_title, "Hello World" in the partial, it IS accessible in the LAYOUT, but it is NOT in the VIEW - content_for?(:view_content_title)

Why ? What should I do about it ?

Upvotes: 3

Views: 6728

Answers (2)

David K.
David K.

Reputation: 339

One possible workaround is that layouts do have access to :locals, so you can do something like this:

view_file.html.erb

<%= render partial: "my_partial", layout:"my_layout", locals:{:title=>"Best Answer Ever"} %>

_my_layout.html.erb

<H1> <%= title %> </H1>
<%= yield %>

_my_partial.html.erb

All your content goes here, and this partial also has access to locals if you want to use them.

This will yield:

<H1>Best Answer Ever</H1>
All your content goes here, and this partial also has access to locals if you want to use them.

Upvotes: 1

khustochka
khustochka

Reputation: 2386

I think I found out why. Rails renders the view in a linear way. It renders the view before partial, then a partial, then the rest of the view. I tested that if you call content_for? or render content in a view AFTER rendering the partial - it is OK, if before - content is not present.

And layout is rendered AFTER the view, that is why at that moment content is already available, because the view and the partial is already rendered e.g. directives executed.

Upvotes: 10

Related Questions