Skip to the workspace
Pebellslearn by building
Action View  ›  Lesson

Layouts and yield

Layouts & yield 12 minA layout is the shared page frame; the action's template is inserted where the layout calls yield, and content_for fills named slots such as the page title.

ruby on rails / Layouts and yield

Explore each scene at your own pace.

01 · The rule

The rule

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 :sidebar or content_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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.