gretelを使ってパンくずリストを作っていたところ、この情報をtitleタグに表示できたら便利だと思いました。似た情報を二重管理せずにすみます。
普通に gretel のパンくずリストの情報を定義しておく
config/breadcrumbs.rb
crumb :root do
link 'ホーム', root_path
end
crumb :users do
link 'ユーザーリスト', users_path
end
crumb :user do |user|
link user.name, user_path(user)
parent :users
end
パンくずリストをタイトルタグに流用するための仕組み
app/views/layouts/application.html.haml
!!!
%html
%head
%title= content_for?(:title) ? yield(:title) : "MyApp"
-# 以下省略
# こんなメソッドを作って gretel のヘルパーメソッド breadcrumb の代わりに使う
def breadcrumb_with_title(*args)
breadcrumb(*args)
# タイトルが明示的に指定されてなければ、パンくずリストのテキストを使う
content_for(:title, "#{breadcrumbs.links.last.text} | MyApp") unless content_for?(:title)
end
各ページでは breadcrumb の代わりに breadcrumb_with_title を使う
app/views/users/index.html.haml
- breadcrumb_with_title :users
-# (以下省略)
app/views/users/show.html.haml
- breadcrumb_with_title :user, @user
-# (以下省略)
パンくずリストとは違うタイトルをつけたければ、 content_for で明示的に指定する。
app/views/users/index.html.haml
- content_for :title, 'なんか違うタイトル'
- breadcrumb_with_title :users
-# (以下省略)
余談
gretelのヘルパーメソッドの名前が似てて間違えそうになる。
- breadcrumb ページのパンくずを指定する
- breadcrumbs パンくずリストをレンダリングする
よく間違う人がいるのか、間違ってませんか?ってエラーメッセージを出すようになっている。