LoginSignup
45
67

More than 5 years have passed since last update.

railsでgretelを使ってパンくずリストを作った

Last updated at Posted at 2018-08-11

目的

railsのサイトでgretelを使ってパンくずリストを作成する。SEO対策も兼ねているので下記仕様。

  • 構造化データ
  • タグに階層構造をつける
  • 階層にリンクをつけてタグの一覧に飛べるようにする
  • 親がないときとある時で階層が違う

gretel導入

document

install

gem "gretel"
$ bundle install

fileの設定

設定fileを下記コマンドで作成

$ rails generate gretel:install
config/breadcrumb.rb
# Root crumb
crumb :root do
  link "Home", root_path
end

# Issue list
crumb :issues do
  link "All issues", issues_path
end

# Issue
crumb :issue do |issue|
  link issue.title, issue
  parent :issues
end

viewに設置

<% breadcrumb :issue, @issue %>

上記で各ページでどこまでのパンくずを出すのか設定する。実際にパンくずが出るのは下記を記述した箇所

<%= breadcrumbs pretext: "You are here: ", separator: " &rsaquo; " %>
  • pretext→パンくずリストの前のテキスト
  • separator→パンくずの間の区切り

親の設定

config/breadcrumb.rbのcrumbとendの間にparentを設定することで親を設定することができる。

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

# user#index
crumb :users do
  link "Users", users_path
  parent :root
end

上記でparentにrootを設定。

リンクをつける

リンクの設定

リンクはconfig/breadcrumb.rbのcrumbとendの間にlinkを下記のように設定する。

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

# user#index
crumb :users do
  link "Users", users_path
  parent :root
end

構造化データ

semantic: trueでgretelで構造化データを作ることができる。gretelの場合data-vocabularyで設定される。

root>親カテゴリ>記事名で親カテゴリページでタグを出したい場合

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

crumb :tag do |tag|
  if current_page?(:controller => 'post', :action => 'show')
    show_post_tag_id = TagMap.find_by(post_id: params[:id]).tag_id
    show_post_tag = Tag.find_by(id: show_post_tag_id)
    link show_post_tag.name
  else
    tag_page = Tag.find_by(id: params[:id])
    link tag_page.name
  end
  parent :root
end

crumb :show_title do |show_title|
  show_title = Post.find_by(id: params[:id])
  link show_title.title
  parent :tag
end
45
67
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
45
67