In Rails views, how do content_for, yield :name, content_for? and provide pass a per-page title and extra head tags to the layout?
answer
- named regions in one view flow
- content_for appends unless flush: true
- content_for(:title) is nil when empty
- yield :title is an empty string
- provide for streamed templates
basics
~20 sIn Rails, content_for :name stores HTML in a named region, appending on each call; the layout reads it with yield :name or content_for(:name); content_for? tests whether it is filled; provide stores the same way but is built for streamed templates.
solid answer
~40 s`content_for :title, @exhibit.title` or a block form stores content under a name; a second call appends unless it passes `flush: true`. Strings are escaped as they are stored and blocks are captured as html-safe markup. The layout reads the region with `yield :title` or `content_for(:title)`, which differ when nothing was stored: `content_for` returns `nil`, so `content_for(:title) || "City Museum"` works, while `yield :title` returns an empty string, so the same fallback never fires. `content_for?(:sidebar)` is true when the region has content, handy for switching a layout class. `provide` stores like `content_for` but, under `render stream: true`, lets the waiting layout continue at once instead of waiting for more content.
code
erb · 12 lines<%# app/views/exhibits/show.html.erb %>
<% content_for :title, @exhibit.title %>
<% content_for :head do %>
<meta name="description" content="<%= @exhibit.summary %>">
<% end %>
<h1><%= @exhibit.title %></h1>
<%# app/views/layouts/application.html.erb (excerpt) %>
<title><%= content_for(:title) || "City Museum" %></title>
<%= yield :head %>
<body class="<%= content_for?(:sidebar) ? "two-col" : "one-col" %>">go deeper
Know that content_for :name fills a region and yield :name prints it in the layout.
Explain append versus flush:, the nil-versus-empty-string difference between content_for and yield, and content_for? for layout decisions.
Catch the timing bugs: regions written inside the layout or inside cached fragments, and when provide matters for streaming.
Define the small set of named regions every layout offers, so pages and teams share one contract for titles, head tags and sidebars.
## Regions instead of variables A Rails layout often needs page-specific pieces in places the page's own markup cannot reach: the `<title>`, extra `<meta>` tags in `<head>`, a sidebar. Action View keeps a per-render **view flow**, a hash of named regions, each an `ActiveSupport::SafeBuffer`. The unnamed region holds the action's template output; every other name is created by a view. ## Writing a region | Call | Effect | |---|---| | `content_for :title, "Impressionism"` | appends the string, escaped | | `content_for :head do ... end` | captures the block's HTML and appends it | | `content_for :title, "Shop", flush: true` | replaces the region instead of appending | | `provide :title, "Impressionism"` | appends like `content_for`, escaped; under streaming, wakes the layout waiting for this key | Points worth being exact about: - **Appending is the default.** Two `content_for :title` calls, say one in the template and one in a partial, produce both strings joined. Use `flush: true` when a later call should win. - **Escaping happens on the way in.** A string is appended to a SafeBuffer, so `<` in a title becomes `<`; a block is captured with the usual `<%= %>` escaping inside it. Avoid passing raw strings together with `flush: true`: in 8.1 that path stores the string as a new SafeBuffer without escaping it, so pass a block, or escape the value yourself, when it can contain user input. - **Writing returns nil.** `<% content_for :title, ... %>` is the normal spelling; `<%= %>` would print nothing anyway. ## Reading a region | Expression | Empty region | Filled region | Works in helpers | |---|---|---|---| | `yield :title` | `""` (empty SafeBuffer, truthy) | the HTML | no | | `content_for(:title)` | `nil` | the HTML | yes | | `content_for?(:title)` | `false` | `true` | yes | This difference is a classic bug. `<%= yield(:title) || "City Museum" %>` never shows the default, because an empty string is truthy in Ruby. The generated Rails 8.1 layout uses `content_for(:title) || "App Name"` for exactly this reason. `content_for?` is the right test for layout decisions, such as adding a `with-sidebar` class to `<body>` only when a page filled `:sidebar`. ## Timing The template renders completely before the layout, so a region filled anywhere in the template or its partials is visible to the whole layout. Two cases break that: 1. A `content_for` call **inside the layout** after the `yield :name` that reads it is too late; the layout has already printed that spot. 2. Content inside a **cached fragment** is not replayed: on a cache hit, the `content_for` calls inside the cached block do not run, so the region stays empty. Keep `content_for` calls outside cached blocks. ## What `provide` is for With a streamed response (`render stream: true`), Rails renders the layout first and pauses it at each `yield :name` until the template supplies that region. `content_for` may be called several times for one key, so the layout keeps waiting until the template finishes. `provide` signals that the value is complete, so the layout resumes right away and can flush the `<head>` to the browser sooner. Without streaming, `provide` and `content_for` behave the same, which is why many apps use `provide :title` out of habit. ## Wrapping regions in helpers `yield` only works in templates and layouts, while `content_for` also works inside helper methods. That makes small helpers a tidy way to standardise regions: ```ruby module ApplicationHelper def page_title(text) content_for :title, text end def page_title_or(default) content_for(:title) || default end end ``` Pages then call `<% page_title @exhibit.title %>`, and the layout calls `page_title_or("City Museum")`, so the nil-versus-empty rule lives in one place. ## A museum example The exhibit page calls `content_for :title, @exhibit.title` and adds a `<meta name="description">` with `content_for :head do ... end`; the staff dashboard fills `:sidebar`. The layout prints `content_for(:title) || "City Museum"`, `yield :head`, and wraps the main column in `content_for?(:sidebar) ? "two-col" : "one-col"`.
- Why does `<%= yield(:title).presence || "City Museum" %>` work when `yield(:title) || ...` does not?`yield :title` returns an empty SafeBuffer for an unfilled region, and an empty string is truthy, so `||` never reaches the default. `presence` turns a blank string into `nil`, which is what `content_for(:title)` already does internally.
- A partial and its parent template both call `content_for :title`. What does the layout show?Both values, joined in the order the calls ran, because `content_for` appends. To let the later call replace the earlier one, it passes `flush: true`, ideally with a block so the content is still escaped.
The view flow is a set of labelled envelopes on the layout's desk. Pages drop notes into envelopes by name, several notes per envelope unless flush: replaces them, and the layout opens each envelope where it needs it. content_for hands back nothing for an empty envelope, while yield hands back the empty envelope itself, which is why only content_for supports a fallback.
- yield :title returns nil when no page set a title.
- A second content_for call for the same name replaces the first.
- content_for and yield :name cannot be read from a helper method.
- provide is the newer name for content_for and behaves the same everywhere.
- Strings passed to content_for are stored unescaped.