Layouts and yield
Every page in Bookclub has the same header, navigation, flash messages and footer. You do not repeat them in each template. They live once in a layout, and each action's template is poured into it.
The rule
The layout is the frame; yield is the hole the page fills.
<%# app/views/layouts/application.html.erb %>
<!DOCTYPE html>
<html>
<head>
<title><%= content_for(:title) || "Bookclub" %></title>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag "application" %>
<%= javascript_importmap_tags %>
</head>
<body>
<header><%= link_to "Bookclub", root_path %></header>
<% flash.each do |type, message| %>
<p class="flash <%= type %>"><%= message %></p>
<% end %>
<main><%= yield %></main>
<aside><%= yield :sidebar %></aside>
</body>
</html>yield(no name) — where the action's template goes.yield :sidebarorcontent_for(:sidebar)— a named slot a template can fill.- A template fills a slot with
content_for:
<%# app/views/books/show.html.erb %>
<% content_for :title, @book.title %>
<% content_for :sidebar do %>
<p>More by <%= @book.author %></p>
<% end %>
<h1><%= @book.title %></h1>This works because Rails renders the template first, then the layout. By the time the layout reaches <title>, the template has already filled it.
Which layout? By default application.html.erb. If app/views/layouts/books.html.erb exists, BooksController uses it instead. You can also choose: layout "admin" in a controller, or render :show, layout: false for a bare response.
The shortcut
Ask "is it on every page, or just this one?" Every page → layout. Just this page → template. Just this page, but it must appear in the layout's area (title, sidebar, extra script) → content_for in the template, yield :name in the layout.
Every page or one?
Only the show page wants it.
The trap is copying the header into every template "just this once". The next change to the header then needs twenty edits.
Drills
Answer fast — trust the rule.
Where does the action's template appear inside the layout?
How does a template put text into the layout's yield :title?
Why can a template set the page title even though <title> appears near the top of the layout?
app/views/layouts/books.html.erb exists. Which controller uses it automatically?
Remember
- The layout is the frame; yield is the hole the page fills.
- Shortcut: every page → layout; this page → template; this page, layout's area → content_for.
- Trap: copying shared markup into templates.
