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.