LoginSignup
10
11

More than 3 years have passed since last update.

【Rails】ページごとに表示を変える

Posted at

目的

ページごとに共通部分を変えたり、ユーザーの状況によってページ表示される内容を変えたい

前提

deviseを導入している(ユーザー がログインしているか?で使う)

色々なパターン(具体例を提示)

①ユーザーがサインインしているか?で条件分岐
②訪れているページがどこか?で条件分岐
③コントローラーごとに共通部分を分ける
④アクションごとに、共通部分を分ける

他にも色々あるとは思いますが、自分が試した物を書きます。

実装例①ユーザーがサインインしているか?で条件分岐

html.haml

- if user_signed_in?

これはよく使うのが、サインインしていれば新規投稿ボタンが表示されるなど
上記で囲み

user_signed_in?

でログインされていたら表示するという使い方をする

実装例②訪れているページがどこか?で条件分岐

root_path かどうか

current_page?(root_path)

/users/:id が current_user かどうか

current_page?(current_user)

任意のコントローラ/アクションかどうか

current_page?(controller: 'foo', action: 'bar')

 URLが"sign_in"という文字を含む時、link_toを非表示

html.haml
- unless request.path.include?("sign_in")
# URLが"sing_in"をいう文字を[含まない時]、次の処理を実行

  = link_to "サインイン", new_user_session_path

# つまり、"sing_in"をいう文字を含む時、下の処理は実行しない(表示しない)

実装例③コントローラーごとに共通部分を分ける

「app/views/layouts/任意の名前.html.haml」というファイルを用意する

class コントローラ名 < ApplicationController
  layout 'レイアウトファイル名'

  def アクション名
  end
end

実装例④アクションごとに、共通部分を分ける

「app/views/layouts/任意の名前.html.haml」というファイルを用意する

例えばapp/views/layouts/compact.html.hamlを用意

compactの記述を反映させたいアクションに以下の記述をする。

class コントローラ名 < ApplicationController
  def アクション名
    render layout: 'compact'
  end
end

参考文献

https://www.javadrive.jp/rails/template/index3.html
https://qiita.com/Yohei_Shiina/items/ed39dfd74895d54f3cf2

10
11
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
10
11