skip to content

In a Rails controller, how do layout "staff", layout :method, layout false and only:/except: pick a layout, and how does render layout: override them?

level: middleimportance: should knowfreq 42%

answer

  1. String, Symbol, Proc, false or nil
  2. a method may return nil to fall back
  3. excluded actions use the implied lookup
  4. subclasses inherit the macro
  5. render layout: wins for one call

basics

~20 s

In a Rails controller, layout "staff" names a template in app/views/layouts, layout :method decides per request, layout false turns layouts off, and only:/except: limit which actions get it; render layout: overrides all of that for one render.

solid answer

~40 s

The `layout` class macro takes a String (a template name, looked up under `layouts/`), a Symbol (a method called on each request, which returns a name, `false` for none, or `nil` to fall back to the default lookup), a Proc, `false` (no layout) or `nil` (reset to the implied, controller-named lookup); `true` raises `ArgumentError`. Subclasses inherit the setting. `only:` and `except:` limit the actions it applies to, and an excluded action does not lose its layout: it falls back to the implied lookup, which in a typical app ends at `layouts/application`. To render one action bare, use `layout false, only: ...` in a separate controller, or `render layout: false`. `render layout: "print"` picks a layout for that one call.

code

ruby · 20 lines
ruby
class Staff::BaseController < ApplicationController
  layout "staff"
end

class Staff::ExhibitsController < Staff::BaseController
  layout "print", only: :label   # index, show... fall back to the implied lookup,
                                 # not to "staff" and not to no layout
  def label
    @exhibit = Exhibit.find(params.expect(:id))
  end
end

class DashboardsController < ApplicationController
  layout :dashboard_layout

  private
    def dashboard_layout
      Current.user&.staff? ? "staff" : nil   # nil = default lookup
    end
end

go deeper

for a junior

Know layout "name" and layout false, and that render layout: false renders one response bare.

for a middle

Explain the argument types, the nil fallback from a layout method, inheritance down the controller tree and the per-call layout: option.

for a senior

Spot the only:/except: fallback trap and structure base controllers so each area of the app gets its shell without per-action overrides.

for a principal

Decide how many shells the product needs and where the choice lives, base controllers or runtime methods, so it stays predictable.

## The macro and its argument types `layout` is a class method from `ActionView::Layouts`, available in every controller. What it does depends on the argument: | Argument | Meaning | |---|---| | `"staff"` | use `app/views/layouts/staff.*`; `"layouts/staff"` is the same | | `:staff_or_public` | call this (usually private) method on each request | | `->(controller) { ... }` or `proc { ... }` | evaluate per request; without an argument it runs in the controller's context | | `false` | render with no layout | | `nil` | ignore any inherited setting and use the implied lookup again | | `true` | raises `ArgumentError` | A method or proc may return a String, `false`, or `nil`. `nil` means "use the default lookup", which makes a method like `current_staff ? "staff" : nil` a clean way to switch only when needed. Any other return value raises `ArgumentError`. ## Inheritance Layout settings cascade down the controller hierarchy, and the most specific one wins: - `ApplicationController` with no `layout` call uses the implied `layouts/application`. - `Staff::BaseController < ApplicationController` with `layout "staff"` makes every staff controller use the staff layout. - `Staff::ReportsController < Staff::BaseController` with `layout false` renders reports without any layout. - A subclass with `layout nil` drops the parent's explicit choice and searches for a layout named after itself first. If a String layout cannot be found in any format, rendering raises `ActionView::MissingTemplate`. If it exists only in another format, such as a JSON response under an `.html.erb` layout, the render quietly goes without a layout. ## `only:` and `except:`: the trap `layout "print", only: :label` applies the print layout to `label`. Many developers expect every other action to render bare; it does not. For an action excluded by the condition, Rails skips the named layout and runs the **implied** lookup: a layout named after the controller, then each ancestor's implied lookup, which in a normal app finds `layouts/application`. The API documentation's own example renders the excluded action bare only because that controller inherits straight from `ActionController::Base` and has no default layout to fall back to. To make one action render bare: 1. call `render layout: false` in that action; or 2. move it to a controller that declares `layout false`; or 3. set `self.action_has_layout = false` before rendering. ## `render layout:` for a single response `render layout:` on one call wins over the macro: - `render layout: "print"` uses `layouts/print`; - `render layout: false` (or `nil`) renders without a layout; - `render layout: true` uses the default layout and raises if there is none. Renders that skip layouts by default, such as `render plain:` or `render html:`, get one only when `layout:` is passed. Other `render` options belong to the controller-rendering topic; `layout:` is the one that touches layouts. ## Choosing a form 1. One shell for a whole area of the app: a String on that area's base controller. 2. A shell that depends on the request or the user: a Symbol naming a private method, returning `nil` when the default should apply. 3. One action that differs: `render layout:` inside that action, not a conditional macro. 4. A controller that never wants a layout, such as one serving fragments: `layout false`. ## A museum example The public site uses `application.html.erb`. Staff pages live under `Staff::` controllers whose base class declares `layout "staff"`. The visitor-label action prints badges with `render layout: "print"`. A docent dashboard picks its shell per user with `layout :dashboard_layout`, whose method returns `"staff"` for staff and `nil` for volunteers, so volunteers fall back to the normal lookup.

  • In the snippet, which layout does `Staff::ExhibitsController#index` use, and why is it not `staff`?
    The `layout "print", only: :label` call replaces the inherited setting for this class, and its condition applies to the inherited lookup as well. For `index` Rails runs the implied lookup: `layouts/staff/exhibits`, then each parent's implied name, ending at `layouts/application`. To keep `staff` for the other actions, choose the layout in a method or use `render layout: "print"` in `label`.
  • Why prefer a Symbol method over a Proc for a runtime layout choice?
    A private method is easier to read, test and override in a subclass, and the API documentation calls it the preferred approach. A Proc works the same way but hides logic inside the class body.

  • Actions excluded by only: or except: are always rendered without a layout.
  • layout true forces the default layout on every action.
  • A layout method must return a String; returning nil raises an error.
  • layout nil and layout false both mean no layout.
  • render layout: only works for actions that have no layout macro.