LoginSignup
5
2

More than 5 years have passed since last update.

Rails Controller で layout を複数呼び出す

Last updated at Posted at 2018-08-21

Rails Controller で layout を複数呼び出すと後勝ちで上書きされる

some_controller.rb
class SomeController < ApplicationController
  layout 'layout_for_index', only: :index
  layout 'layout_for_show', only: :show

  def index; end
  def show; end
end

結果

  • some#index -> デフォルトの layout が適用される
  • some#show -> layout_for_show が適用される

layout にはメソッド名やprocを渡せるのでこんな感じで書けばいける

some_controller.rb
  layout :determine_layout
  ...
  def determine_layout
    case action_name
    when 'index' then 'layout_for_index'
    when 'show' then 'layout_for_show'
    end
  end

該当コード見ると普通に代入してるので当然の動きですね

rails/actionview/lib/action_view/layouts.rb
def layout(layout, conditions = {})
  include LayoutConditions unless conditions.empty?

  conditions.each { |k, v| conditions[k] = Array(v).map(&:to_s) }
  self._layout_conditions = conditions

  self._layout = layout
  _write_layout_method
end

source: rails/actionview/lib/action_view/layouts.rb:267

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2