パンくず機能とは
パンくずを実装する利点は、Webサイトを利用しているユーザーが、どのページにアクセスしているのか一目でわかることです。アクセス場所がわかることによって、サイトの巡回が行いやすくなります。
例として、旅行会社のホームページで、旅行先を調べている場面を考えます。トップページに最初の選択肢で、「国内」と「海外」があり、「国内」を選択したとします。次に「国内」の中には、北海道などの観光地が選択肢として表示されます。
「トップページ」の中に「国内」があり、「国内」の中に「北海道」があるように、要素同士が紐付いており、親要素・子要素の関係であることを指します。
Gemをインストール
Gemfile
gem 'gretel'
ターミナル
bundle install
パンくずの設定
ターミナル
rails g gretel:install
- config/breadcrumbs.rbのファイルが生成されます。
ファイルの記述方法は以下のようになります。
config/breadcrumbs.rb
crumb "現在のページ名(表示させるビューにもページ名記述)" do
link "パンくずリストでの表示名", "アクセスしたいページのパス"
parent :親要素のページ名(前のページ)
end
config/breadcrumbs.rb
crumb :root do
link "Home", root_path
end
crumb :tweets do
link "国内旅行", hoge_index_path
parent :root
end
crumb :contacts do
link "北海道", huga_index_path
parent :hoge
end
ビューを編集
views/layouts/application.html.erb
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Breadcrumb</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>
<%= breadcrumbs separator: " › " %>
<%= yield %>
</body>
</html>
separator: " ›”は、パンくず間の区切りである「>」を示します。
各indexファイルの編集
app/views/top/index.html.erb
<p><%= link_to "国内旅行へ", hoge_index_path %></p>
<% breadcrumb :root %>
app/views/hoge/index.html.erb
<p><%= link_to "北海道へ", huga_index_path %></p>
<% breadcrumb :hoge %>