6
2

More than 3 years have passed since last update.

【Rails】部分テンプレートの一部を特定のページでのみ表示するには?

Posted at

共通の記述を部分テンプレート化したけど、ページによって一部分だけ記述を変えたいときってありますよね。
そんなときは、current_page?メソッドが便利です!

current_page?メソッドとは?

表示中のページのパスを判定できるメソッドです。
引数にしたパスが表示中のページと同じかどうかを判定してくれています。同じであればtrueを返します。

current_page?(判定したいパス)

実際にHTMLファイルで使用する際は、以下のようにif文を用いて記述します。

<% if current_page?(root_path) %>
  <div>現在のページはトップページです</div>
<% end %>

また、複数のページを指定することもできます。

<% if current_page?(root_path, 〇〇_path, XX_path) %>

参考記事

https://railsdoc.com/page/current_page_q
https://qiita.com/zenizh/items/8b684eefc989d9a56427
https://yabecchi.com/?p=437

6
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
6
2