こんにちは😁
ヘッダーやフッターのないトップページからログインし、ヘッダーやフッターのある管理画面へ遷移するようなサイトを作る際に、レイアウトにapplication.html.erbを使わずにトップページを作りたいと思ったので書いておきます。
layouts/application.html.erb
まず、application.html.erbはこんな感じです。
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= render 'shared/head' %>
</head>
<body>
<div id="wrapper">
<%= render 'shared/header' %>
<%= render 'shared/left_sidebar' %>
<div class="content-page">
<!-- Start content -->
<div class="content">
<%= yield %>
</div>
</div>
<%= render 'shared/right_sidebar' %>
<footer class="footer">
</footer>
</div>
</body>
</html>
layouts/index.html.erbを作成
viewsのlayoutsフォルダに、index.html.erbを作成します。
このファイルは、トップページのapplication.html.erb的な扱いになります。
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= render 'shared/head' %>
</head>
<body>
<div id="wrapper">
<%= yield %>
</div>
</body>
</html>
ビューにtopsフォルダを作成
viewsにtopsフォルダを作成して、中にindex.html.erbを作成します。
このindex.html.erbが、layouts/index.html.erbのyield部分になります。
Topsコントローラを作成する
手動でtops_controller.rbを作成します。
中身は下記のような感じで、indexメソッドを作成して、layoutを定義して半角スペースの後にはレイアウトに指定するビューの名前を入れます。(今回の場合はlayouts/index.html.erb)
layoutを定義することで、application.html.erb以外のレイアウトを使うことができるようになります。
tops_controller.rb
class TopsController < ApplicationController
layout 'index'
def index
end
end
ルートページに指定する
routes.rb
Rails.application.routes.draw do
root 'tops#index'
end
完成!
これでレイアウトにlayouts/index.html.erbを指定したので、トップページにヘッダーやフッターがなくなったと思います😁