LoginSignup
0
1

More than 3 years have passed since last update.

[Rails]パンくずリストを作る

Last updated at Posted at 2020-07-13

対象読者

  • Railsでパンくずリストを実装したい人。
  • 使い方忘れた人。
  • 初学者向けになっています。内容も初歩的なところを解説しています。

gretelって何?

パンくずリストです。ヘンゼルとグレーテルの話のやつ。
パンくず落としていって自分の辿って来た道がわかる。

Gemのインストール

gretelのgithubはこちらから

Gemfile
gem 'gretel'

bundle installしたら必要なファイルを生成します。

$ bundle install
$ rails g gretel:install

以下のようにファイルが生成されればOKです。

Running via Spring preloader in process 6675
      create  config/breadcrumbs.rb

これが中身。

breadcrumbs.rb
crumb :root do
  link "Home", root_path
end

# crumb :projects do
#   link "Projects", projects_path
# end

# crumb :project do |project|
#   link project.name, project_path(project)
#   parent :projects
# end

#
#
#以下省略
#
#
#

設定を書く

先ほどのbreadcrumbs.rbというファイルはパンくずを落としていく設定ができるファイルになります。
例えば、

Home > カテゴリ

のようなパンくずを落としていきたい場合は

breadcrumb.rb
crumb :root do
  link "Home", root_path
end

crumb :articles do
  link "記事一覧", articles_path #パスは該当ページのパスを書く(ここでは記事一覧)
  parent :root
end

カテゴリの前のページをHomeにしたいのでparentは:rootを指定します。

Viewに表示させる

あとはViewの方で出力してあげるだけです。

application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title>パンくずアプリ</title>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>
  <body>
    <%= breadcrumbs separator: " &rsaquo; " %> #ここを追加
    <%= yield %>
  </body>
</html>
articles/index.html.erb
<% breadcrumb :articles %>

これで

Home > 記事一覧

のパンくずリストが出来上がります。

登録してあるデータをパンくずに表示したい

Home > 記事一覧 > [記事のタイトル]

みたいにしたい場合は少し工夫が必要になります。

以下のように、Viewの方からbreadcrumb.rbへデータを送ってあげないといけません。
今回は記事のタイトルをパンくずとして出力してあげたいので、@articleを第2引数に指定してデータを渡してあげます。

articles/show.html.erb
<% breadcrumb :article_show, @article %>
breadcrumb.rb
crumb :root do
  link "Home", root_path
end

crumb :articles do
  link "記事一覧", articles_path #パスは該当ページのパスを書く(ここでは記事一覧)
  parent :root
end

crumb :article_show do |article| #ここで受け取ってる
  link article.title, article_path(article) #<表示する文字列>、<記事詳細のパス>
  parent :articles  #親を設定する
end

Home > 記事一覧 > パンくずリストを作ってみた

作成日時を出力させたいと思ったら、

breadcrumbs.rb
crumb :article_show do |article|
  link article.created_at, article_path(article) #変更(title => created_at)
  parent :articles
end

に変更すればOKです。

0
1
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
0
1