๐Ÿ–ผ๏ธ

Layouts & yield

Manage common page structure with layouts

Layout is the common HTML skeleton applied to all pages.

<%# app/views/layouts/application.html.erb %>
<!DOCTYPE html>
<html>
<head>
  <%= csrf_meta_tags %>
  <%= stylesheet_link_tag 'application' %>
</head>
<body>
  <nav>Common Navigation</nav>

  <% if content_for?(:sidebar) %>
    <aside><%= yield :sidebar %></aside>
  <% end %>

  <main><%= yield %></main>  <%# Each page's content inserted here %>

  <footer>Common Footer</footer>
</body>
</html>

content_for:

<%# app/views/posts/show.html.erb %>
<% content_for :sidebar do %>
  <nav>Sidebar content</nav>
<% end %>

<h1>Main content</h1>  <%# This part goes into yield %>

Layout specification:

  • layout 'admin' โ€” per controller

  • render layout: 'special' โ€” per action

  • layout false โ€” render without layout

Key Points

1

app/views/layouts/application.html.erb โ€” default layout

2

yield โ€” where each action's view content is inserted

3

content_for :name โ€” insert content in specific areas (sidebar, head, etc.)

4

yield :name โ€” output content inserted by content_for

5

layout "admin" โ€” specify different layout in controller

6

content_for?(:name) โ€” check if content exists for the area

Pros

  • Manage common HTML structure in one place
  • Flexible per-area content insertion with content_for
  • Easy layout switching
  • DRY โ€” same nav/footer on all pages

Cons

  • Hard to follow flow when overusing content_for
  • Nested layouts not supported (gem required)
  • Hard to manage when inserting JS/CSS via content_for

Use Cases

Site-wide common layout Separate admin/user layouts Per-page sidebar/meta tag insertion Email template layout