Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท Views and Templates

Layouts and Partials

Learn how Rails layouts wrap every page with yield, how partials share view fragments with locals and collections, and how content_for fills named regions. Includes a runnable layout and partial engine.

A website has repeating parts: a header, a navigation bar, a footer. Copying that HTML into every template would be a maintenance nightmare. Rails solves this with two tools. A layout is the frame around a page: it holds the <html>, <head>, navigation and footer, and has a spot where the page's own content goes. A partial is a reusable fragment, such as one article card or a form, that you render from many places.

This lesson explains both, plus content_for (a way for a page to send content to a region of the layout) and rendering collections. The Rails templates are read-only snippets, and the runnable examples are a small layout-and-partial engine built with the standard erb library.

Layouts

The default layout is app/views/layouts/application.html.erb. Every view is rendered inside it:

ERB
<%# app/views/layouts/application.html.erb  (read-only) %>
<!DOCTYPE html>
<html>
  <head>
    <title><%= content_for?(:title) ? yield(:title) : "My Blog" %></title>
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag "application" %>
    <%= javascript_importmap_tags %>
  </head>
  <body>
    <%= render "shared/navbar" %>
    <% flash.each do |type, message| %>
      <div class="flash <%= type %>"><%= message %></div>
    <% end %>
    <main>
      <%= yield %>
    </main>
  </body>
</html>

The bare yield is where the page's view goes. Rails renders the view first, saves its output, then renders the layout and drops that output in at yield.

flowchart TD
  A["articles/show.html.erb<br/>renders first"] -->|"its HTML"| B["layouts/application.html.erb<br/>yield inserts it"]
  P["shared/_navbar partial"] --> B
  B --> R["Final page sent to browser"]

The view is rendered first, then wrapped by the layout, which can include partials.

Choosing a layout

A controller can choose another layout, for example for an admin area:

Ruby
# read-only
class Admin::BaseController < ApplicationController
  layout "admin"        # app/views/layouts/admin.html.erb
end

class SessionsController < ApplicationController
  layout false          # no layout at all
end

render :show, layout: "minimal"   # per render call

content_for: filling named regions

Sometimes a page needs to put something into the layout outside the main yield, such as a page-specific title or extra scripts. content_for stores a block under a name, and the layout reads it with yield(:name).

ERB
<%# read-only: in show.html.erb %>
<% content_for :title, @article.title %>
<% content_for :head do %>
  <meta name="robots" content="noindex">
<% end %>
<h1><%= @article.title %></h1>
ERB
<%# read-only: in the layout %>
<title><%= yield(:title) %> | My Blog</title>
<%= yield(:head) %>

Partials

A partial is a template whose name starts with an underscore. app/views/articles/_article.html.erb is rendered with render "article" (without the underscore). Pass data through locals:

ERB
<%# app/views/articles/_article.html.erb  (read-only) %>
<article>
  <h2><%= link_to article.title, article %></h2>
  <p><%= truncate(article.body, length: 100) %></p>
</article>
ERB
<%# read-only: using it %>
<%= render "article", article: @article %>
<%= render partial: "article", locals: { article: @article } %>
<%= render "shared/footer" %>                     <%# looks in app/views/shared/_footer %>

To render a list, pass the collection. Rails loops for you, sets a local named after the partial, and is faster than writing your own loop with render inside:

ERB
<%# read-only %>
<%= render partial: "article", collection: @articles %>
<%= render @articles %>                           <%# shortcut: uses each record's model name %>
<%= render partial: "article", collection: @articles, spacer_template: "divider" %>

When the collection is empty, render @articles returns nil, so you can write render(@articles) || "No articles yet".

Layout or partial?

Layout The frame around a page.
Partial A reusable fragment.
content_for Send content to a named spot.
1 / 2

Stand-in: a tiny layout and partial engine

This stand-in uses ERB to build the same machinery: a render method that looks up partials by name, passes locals, renders collections, and wraps everything in a layout with yield. The "files" live in a Hash instead of folders.

Ruby Stand-in: layout, partial, collection and content_for

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Two behaviours to notice. The view articles/index runs first and sets the title with content_for; the layout then reads it. And render(partial: ..., collection: []) returns nil, so the || fallback shows "Nothing yet". The yield inside the layout: the engine passes the already-rendered body via a block so yield works inside ERB#result.

Nested layouts and shared partials

Folder app/views/shared/ is the conventional home for partials used by many controllers (render "shared/navbar"). Rules to follow:

  • Pass locals explicitly. A partial that silently reads @article only works from one place.
  • Use the cache. Fragment caching wraps a partial: <% cache article do %> ... <% end %>. Rails can skip rendering unchanged items.
  • Do not over-nest. A page built from six levels of partials is hard to debug. Extract a partial when a fragment repeats or has a clear name.

For richer components, many teams use ViewComponent, which turns a fragment into a Ruby class with its own tests. It is a gem and so read-only here, but it builds on exactly the ideas above.

If a partial name appears in an error such as Missing partial articles/_article, check three things: the file starts with an underscore, it sits in the folder named in the render call, and the format extension matches (.html.erb).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does the page's own view appear inside a layout?

    The layout's bare yield is replaced by the rendered view.
  2. 2. What is the file name of the partial rendered by render "article" inside the articles views?

    Partial files begin with an underscore, but the render call leaves it out.
  3. 3. How do you send a page-specific title into the layout?

    content_for stores content under a name that the layout reads with yield(:name).
  4. 4. Why is render @articles often preferred over looping with render inside the loop?

    Collection rendering loads the partial once and sets the local variable for each item.

Summary

  • A layout wraps every page; its bare yield is where the view goes; layout "admin" or layout false changes it.
  • content_for / yield(:name) lets a view fill extra regions such as the title or head.
  • Partials are files starting with _; pass locals explicitly instead of reading instance variables.
  • render @articles or render partial:, collection: renders a list; an empty collection returns nil.
  • Cache and extract fragments thoughtfully; do not nest deeply.

Next: View Helpers and Forms