LoginSignup
10
8

More than 5 years have passed since last update.

railsアプリにパンくずリストを実装するGem ~breadcrumbs_on_rails~

Last updated at Posted at 2016-04-15

最終目標

  • railsアプリにカスタム構造のパンくずリストの設置
  • viewはslimで実装

SEOにいいパンくずのタグ構造は「いろんなキュレーションサイトのパンくずリスト比較」(http://chmod.tech/?p=867) を参考にする.

すでにbreadcrumbs_on_railsでパンくずリストが実装できている前提で進める(controllerのadd_breadcrumbとかを省略してる)

lib/custom_breadcrumbs_builder.rb

lib/custom_breadcrumbs_builder.rb
class CustomBreadcrumbsBuilder < BreadcrumbsOnRails::Breadcrumbs::Builder
  def render
    @context.render "/article/breadcrumbs", elements: @elements
  end
end

pathは次に追加するカスタムしたパンくずのviewがを指定(今回ならapp/views/article/_breadcrumbs.html.slim)

view(カスタムしたパンくずのタグ構造)

app/views/article/_breadcrumbs.html.slim
- if elements.present? and elements.length > 1
  ul
    - elements[0..-2].each do |element|
      li [itemscope itemtype="http://data-vocabulary.org/Breadcrumb"]
        - if element.path.present?
          a href="#{element.path}" itemprop="url"
            span itemprop="title"
              = element.name
        - else
          span itemprop="title"
            = element.name
  li [itemscope itemtype="http://data-vocabulary.org/Breadcrumb"]
    span itemprop="title"
        = elements.last.name

erbなら下のようになる(動作未確認)

<% if elements.present? and elements.length > 1 %>
    <ul itemscope itemtype="http://data-vocabulary.org/Breadcrumb">
    <% elements[0..-2].each do |element| %>
        <li itemscope itemtype="http://data-vocabulary.org/Breadcrumb">
        <% if element.path.present? %>
            <a itemprop="url" href="<%= element.path %>"><span itemprop="title"><%= element.name %></span></a>
        <% else %>
            <span itemprop="title"><%= element.name %></span>
        <% end %>
        </li>
    <% end %>

        <li itemscope itemtype="http://data-vocabulary.org/Breadcrumb">
          <span itemprop="title"><%= elements.last.name %></span>
        </li>
    </ul>
<% end %>

を追加

view(パンくず表示箇所)

表示する場所の呼び出しを変える

= render_breadcrumbs builder: ::CustomBreadcrumbsBuilder

erbなら

<%= render_breadcrumbs builder: ::CustomBreadcrumbsBuilder %>

libの読み込み(超重要!!!!!)

config/applecation.rb
config.autoload_paths += Dir[Rails.root.join('lib')]

を追加
これをしないとlibに追加したcustom_breadcrumbs_builder.rbを読み込んでくれなくてNO NAME ERRORになる.

まとめ

  • libの読み込みを書かないといけないところでつまずいた.
  • 表示できてる前提からのカスタムの仕方しか書かなかったので、時間があったらgemの追加から書きたい.

参考サイト

http://loumo.jp/wp/archive/20150711000024/
http://chmod.tech/?p=867
http://chmod.tech/?p=896

10
8
2

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
10
8