How does Ruby on Rails "content_for: title" get what is assigned later?

Short question: how can

<% content_for :title do 'Showing product' end %>

set :titlefor main layout?


Details:

We can use in the layout of the application application.html.erb

<title><%= content_for :title %>
  ...
  <%= yield %>

and I think it yieldreturns the contents of a subpage, for example, from show.html.erbwhere it contains:

<% content_for :title do 'Showing product' end %>

How :titlecan somehow be used by something higher yield? I thought that part is evaluated first title, and then yield, since it :titlecan retroactively set the contents of a tag <title>?

+5
source share
2 answers

Short answer: cheating.

: ActionView , , , . , . content_for , .

+8

title application_helper.rb :

module ApplicationHelper
  def title(page_title)
    content_for(:title){ page_title }
    page_title
  end
end

ERB

<% title "Rails Rocks" %>
Other regular content

application.html.erb

<html>
<head>
  <% title = yield(:title).chop! %>
  <title><%= title || 'Default Title' %></title>
</head>
<body>
  <h1 class="title"><%= title %></h1>
</body>
+5

All Articles