skip to content

Partials & Strict Locals

Partials split views into reusable _name files fed by locals:, and collection rendering runs one partial per record with counters. Interviewers probe strict locals and the cost of partials in loops.

part ofRuby on Railsread it →
on this pageshow

explore

questions

4

In a Rails view, how do you render a partial such as _gig.html.erb and pass it data with locals:?

level: juniorimportance: must knowfreq 70%

answer

  1. leading underscore in the file name
  2. render partial: with locals:
  3. render "gig", gig: @gig shorthand
  4. render @gig uses to_partial_path
  5. unpassed local raises; local_assigns doesn't

basics

~20 s

In Rails, a partial is a template whose file name starts with an underscore, such as gigs/_gig.html.erb; render it with render partial: "gig", locals: { gig: @gig }, the shorthand render "gig", gig: @gig, or render @gig via to_partial_path.

solid answer

~40 s

A partial is a template file named with a leading underscore, rendered from another view with `<%= render ... %>`. The long form is `render partial: "gig", locals: { gig: @gig }`; when only a partial and locals are needed, `render "gig", gig: @gig` means the same. A name without a slash is looked up under the current controller's folders, so `"gig"` in `gigs/index` finds `gigs/_gig.html.erb`; `"shared/gig_card"` finds `shared/_gig_card.html.erb`. `render @gig` asks the model for `to_partial_path`, `"gigs/gig"`, and passes the record as the local `gig`. Each key in `locals:` becomes a local variable; referencing one that was not passed raises, while `local_assigns[:key]` returns `nil`, which suits optional values. Partials can read instance variables, but passing locals keeps them reusable.

code

erb · 14 lines
erb
<%# app/views/gigs/show.html.erb %>
<%= render @gig %>

<%# app/views/venues/show.html.erb %>
<%= render "gigs/gig", gig: @venue.next_gig, show_venue: false %>

<%# app/views/gigs/_gig.html.erb %>
<article class="gig">
  <h2><%= gig.band_name %></h2>
  <time><%= l(gig.starts_at, format: :short) %></time>
  <% if local_assigns.fetch(:show_venue, true) %>
    <p><%= gig.venue.name %></p>
  <% end %>
</article>

go deeper

for a junior

Know the underscore naming, render partial: with locals:, the shorthand form and render @gig.

for a middle

Explain where a partial is looked up, how to_partial_path and the namespace prefix work, and local_assigns for optional locals.

for a senior

Keep partials dependent on locals rather than instance variables so they can be reused across controllers and tested in isolation.

for a principal

Set conventions for what becomes a partial, a helper or a component, so shared UI has one home and a clear interface.

## What a partial is A **partial** is a template meant to be rendered inside another template. Its file name starts with an underscore, `app/views/gigs/_gig.html.erb`, and the underscore is dropped when you refer to it: `render "gig"`. Partials keep a long page readable and let one piece of markup, such as a concert-listing card, appear on the index page, the venue page and a search result. ## The ways to call `render` from a view | Call | Partial file | Locals inside | |---|---|---| | `render partial: "gig", locals: { gig: @gig }` | `gigs/_gig.html.erb` (from a `gigs` view) | `gig` | | `render "gig", gig: @gig` | same | `gig` | | `render "shared/gig_card", gig: @gig` | `shared/_gig_card.html.erb` | `gig` | | `render @gig` | `gigs/_gig.html.erb` via `@gig.to_partial_path` | `gig` | | `render partial: "gig", object: @featured` | `gigs/_gig.html.erb` | `gig` (named after the partial) | | `render partial: "gig", object: @featured, as: :show` | `gigs/_gig.html.erb` | `show` | The shorthand `render "gig", gig: @gig` works because a String first argument means "partial" and a Hash second argument means "locals". Any other option, such as `object:` or `layout:`, needs the long `partial:` form. ## How the file is found - A name **without a slash** is looked up under the current controller's view prefixes, so in `gigs/index.html.erb` it means `gigs/_gig`; if that does not exist, it is looked for in the parent controllers' folders, such as `application/_gig`. - A name **with a slash** is taken from `app/views`: `"shared/gig_card"` means `app/views/shared/_gig_card.html.erb`. - **`render @gig`** calls `to_partial_path` on the object. Active Model builds it from the model name as `"gigs/gig"`. Inside a namespaced controller such as `Admin::GigsController`, Rails prefixes it with the namespace first, `admin/gigs/gig`, because `prefix_partial_path_with_controller_namespace` defaults to true. ## Locals versus instance variables Every key in `locals:` becomes a **local variable** in the partial. Two rules follow: 1. Referencing a local that was not passed raises a `NameError`, which Rails reports as an `ActionView::Template::Error` pointing at the partial. 2. `local_assigns` is a Hash of what was passed. `local_assigns[:show_price]` returns `nil` when absent, and `local_assigns.fetch(:show_price, true)` gives a default, so optional values are read through it. A partial can also read the controller's instance variables, such as `@venue`, because it renders in the same view context. That works, but it ties the partial to one controller and hides its inputs. Passing `venue: @venue` as a local makes the partial reusable and its dependencies visible at the call site. ## A concert-listings example The gig card shows the band, the date and, on most pages, the venue. On the venue's own page the venue line is redundant, so the call site passes `show_venue: false`, and the partial reads `local_assigns.fetch(:show_venue, true)`. Every other page simply calls `render @gig`. ## Mistakes that come up in review - Naming the file `gig.html.erb` without the underscore: `render "gig"` will not find it. - Calling `<% render "gig", gig: @gig %>` without the equals sign: the partial renders and the output is thrown away. - Passing `locals:` to the shorthand form as a key, `render "gig", locals: { gig: @gig }`: the partial receives one local called `locals`. - Reaching for instance variables inside a partial that several controllers render, so it breaks wherever the variable is not set. Partials rendered for many records at once, strict signatures through the `locals:` magic comment, and what partials cost in loops are the next steps beyond this basic call.

  • Why does `render "gig", locals: { gig: @gig }` leave `gig` undefined inside the partial?
    In the shorthand form the second argument already is the locals hash, so the partial receives a single local named `locals`, and `gig` is never set. Either write `render "gig", gig: @gig` or use the long form `render partial: "gig", locals: { gig: @gig }`.
  • Inside `Admin::GigsController` views, which file does `render @gig` look for first?
    `admin/gigs/_gig.html.erb`, because Rails prefixes the model's `to_partial_path` with the controller namespace by default. Setting `config.action_view.prefix_partial_path_with_controller_namespace = false` makes it use `gigs/_gig` everywhere.

  • Partial files are named without the leading underscore.
  • Referencing a local that was not passed simply evaluates to nil.
  • render @gig needs the partial name spelled out to find gigs/_gig.
  • Partials cannot see the controller's instance variables at all.
  • render "gig", locals: { gig: @gig } passes gig as a local.
open as a page

In Rails, what do render @gigs and render partial: "gig", collection: do, and how do as:, spacer_template:, gig_counter and gig_iteration work?

level: middleimportance: must knowfreq 55%

basics

~20 s

Rails' render @gigs, or render partial: "gig", collection: @gigs, renders the partial once per element, exposing gig, gig_counter from 0 and gig_iteration; as: renames them, spacer_template: renders between items, and an empty collection returns nil.

open as a page

A Rails concert-listings page renders 500 gig cards with render inside an each loop and is slow; what does a partial cost per call, and what helps?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Each Rails partial render pays for option handling, a template lookup and instrumentation; a collection render pays that once for the whole list. Queries and nested partials inside each card usually cost more and should be fixed first.

open as a page

What does a Rails strict locals magic comment such as <%# locals: (gig:, compact: false) -%> enforce in a partial, and why add one?

level: seniorimportance: should knowfreq 28%

basics

~20 s

A Rails strict locals comment gives a partial a keyword-argument signature: required locals must be passed, unknown ones are rejected, defaults fill the rest, and the partial compiles once instead of once per combination of locals passed.

open as a page