LoginSignup
0
0

【rails】viewの共通applicationを切り分ける

Posted at

やりたいこと

  • deviseを用いたログイン、サインアップ画面と通常のメイン画面とで、共通のviewを切り分けて表示させたい。
  • (例)メニューヘッダー,サイドバーはログイン画面には表示させたくない

やったこと

  1. ユーザー認証用のHTMLを作る

  2. ApplicationControllerに描画の切替を制御する記述をする

ユーザー認証用のHTML(ファイル名は任意)のファイル名で作って、app/views/layouts/配下に作る

app/views/layouts/devise.html.erbで作るとします

devise.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Sample</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <header class="header">
      <div class="header__inner">
        <div class="header__logo">sample</div>
      </div>
    </header>
    <%= yield %>
  </body>
</html>

ApplicationControllerに描画の切替を制御する記述

表示される内容がdevise_controllerかどうかを判断するためにif devise_controller?を記述し、

trueだったらdevise.html.erb

falseだったらapplication.html.erb

を呼ぶようにする

application_controller.rb

class ApplicationController < ActionController::Base
  layout :layout_by_resource

  private

  def layout_by_resource
    if devise_controller?
      'devise'
    else
      'application'
    end
  end
end

参考

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