記事概要
Ruby on Railsにパンくず機能(リンクを設置したリストを画面に表示させる機能)を実装する方法について、まとめる
前提
- Ruby on Railsでアプリケーションを作成している
サンプルアプリ(GitHub)
gretel(Gem)
リンクを設置したリストを画面に表示する機能を実装できるGem
パンくずの親子関係を設定するファイル
confing/breadcrumbs.rb
crumb "現在のページ名(表示させるビューにもページ名記述)" do
link "パンくずリストでの表示名", "アクセスしたいページのパス"
parent :親要素のページ名(前のページ)
end
手順
- gretel(Gem)を導入する
詳細は、こちらを参照 - パンくずのリストを表示する、ビューを作成する
- app/views/users/index.html.erb
<h1>Users#index</h1> <p><%= link_to "ツイートへ", tweets_index_path %></p> - app/views/tweets/index.html.erb
<h1>Tweets#index</h1> <p><%= link_to "コンタクトへ", contacts_index_path %></p> - app/views/contacts/index.html.erb
<h1>Contacts#index</h1> <p>Find me in app/views/contacts/index.html.erb</p>
- app/views/users/index.html.erb
- ブラウザにて、下記のように表示されていることを確認する
- ターミナルで下記コマンドを実行し、パンくずの親子関係を設定するファイルを作成する
% rails g gretel:install -
config/breadcrumbs.rbが作成される - パンくずの親子関係を設定するファイルを編集する
config/breadcrumbs.rb
crumb :root do link "Home", root_path end crumb :tweets do link "ツイート一覧", tweets_index_path parent :root end crumb :contacts do link "コンタクト", contacts_index_path parent :tweets end -
breadcrumbs.rbファイルで実装したパンくずを画面に表示するため、views/layouts/application.html.erbを編集する<!-- 省略 --> <body> <!-- パンくずを画面に表示する --> <%= breadcrumbs separator: " › " %> <%= yield %> </body> </html>separator: " ›”は、パンくず間の区切りである「>」を示す - indexファイルの編集を行う
- app/views/users/index.html.erb
<h1>Users#index</h1> <p><%= link_to "ツイートへ", tweets_index_path %></p> <% breadcrumb :root %> - app/views/tweets/index.html.erb
<h1>Tweets#index</h1> <p><%= link_to "コンタクトへ", contacts_index_path %></p> <% breadcrumb :tweets %> - app/views/contacts/index.html.erb
<h1>Contacts#index</h1> <p>Find me in app/views/contacts/index.html.erb</p> <% breadcrumb :contacts %>
- app/views/users/index.html.erb
- ブラウザで確認する