1
0

More than 3 years have passed since last update.

【Rails】使用するレイアウトファイルを切り替える

Last updated at Posted at 2019-12-18

デフォルトでは全てのviewファイルがapplication.html.erbをレイアウトとして利用するようになっています。
コントローラーやアクションごとに、使用するレイアウトを指定する方法を調べました。

レイアウトファイル側から指定

レイアウトファイルの名前をviews/layouts/hoges.html.erbにすることで、hoges_controller内の全てのアクションに適用されます。

コントローラー側から指定

コントローラーの内上部にlayout '<layoutファイル名の冒頭>'と書き込むことで、そのコントローラー内のアクションで利用するレイアウトファイルを指定することができます。

hoges_controller.rb
class HogesController < ApplicationController
  layout 'another'

  def index
  end
.
.

(レイアウトファイル名がanother.html.erbの場合)

アクションごとに指定

アクション内にrender layout: '<'layoutファイル名の冒頭'>と書き込むことで、そのアクションで利用するレイアウトファイルを指定することができます。

hoges_controller.rb
class HogesController < ApplicationController
  layout 'another'

  def index
    render layout: 'another'
  end
.
.

(レイアウトファイル名がanother.html.erbの場合)

参考

コントローラやアクション毎に使用するレイアウトを切り替える

1
0
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
1
0