The short question is: how can a subpage’s
<% content_for :title do 'Showing product' end %>
set the :title for the main layout?
details:
We can use in the application layout application.html.erb
<title><%= content_for :title %>
...
<%= yield %>
and I think yield returns the content for a subpage, such as from show.html.erb, where it contains:
<% content_for :title do 'Showing product' end %>
How can the :title somehow get used by something above the yield? I thought the title part is evaluated first, and then the yield, so how can the :title retroactively set the content for the <title> tag?
Short answer: By cheating.
Long answer: ActionView redefines yield so it is not the same yield we know and love from good ol’ ruby. In fact the template file is rendered before the layout file and then the yield in the layout file will be substituted by the already rendered template.
content_forblocks are saved into class variables and so you can later access them from your layout.