0
0

More than 1 year has passed since last update.

gretelを使ってパンくずリストを作成

Last updated at Posted at 2022-10-23

目的

scaffoldアプリにてgretelを使ってパンくずリストを作成する。
最低限の内容を学習するため表示させるのはuser_newとuser_showのみにします。

新規の技術・機能の概要

gretelの概要

パンくずリストを作成するgem
edit_パンくず
webサイトの上部などにあるサイトページの位置等を示すリストがパンくずリストです。
gretelの設定ファイルは下記の通り

crumb "ページ名" do
  link "ビューに表示される名前", "リンクされるURL"
  parent :親のページ名(現在の前のページ)
end

表示させるコードは下記

<%= breadcrumbs separator: "区切り文字" %>

執筆時のバージョン

Rails:5.2.6
gretel:4.3.0

実装方法

新規アプリを作成

terminal
rails new gretel_app
cd gretel_app

scaffoldを使ってユーザー登録機能を実装

terminal
rails g scaffold User name:string
rails db:create && rails db:migrate

rootを設定

config/routes.rb
  Rails.application.routes.draw do
    resources :users
+   root "users#index"
  end

gretelの導入

Gemfileにgretelを追加

Gemfile
+ gem 'gretel'
terminal
bundle install

gretelをインストール

terminal
rails g gretel:install

config/breadcrumbs.rbが作成されていることを確認

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

ユーザー登録画面に表示するパンくずリストを設定

config/breadcrumbs.rb
 # 下記を追記
+ crumb :user_new do
+   link "ユーザー登録", new_user_path
+   parent :root
+ end
# それぞれ下記の設定と対応(下記は説明用のコードです)
crumb "ページ名" do
  link "ビューに表示される名前", "リンクされるURL"
  parent :親のページ名(現在の前のページ)
end

パンくずリストの設定を表示させる(application.html.erb)

app/views/layouts/application.html.erb
---省略---
  <body>
    # 仕切りもじは「" &rsaquo; "」で「>」が表示される
+   <%= breadcrumbs separator: " &rsaquo; " %> 
    <%= yield %>
  </body>
---省略---
# それぞれ下記の設定と対応(下記は説明用のコードです)
<%= breadcrumbs separator: "区切り文字" %>

パンくずリストの設定を表示させる(users/new.html.erb)

app/views/users/new.html.erb
 # 下記を追加
+ <% breadcrumb :user_new %>

  <h1>New User</h1>

  <%= render 'form', user: @user %>

  <%= link_to 'Back', users_path %>

サーバーを起動してパンくずリストが表示されることを確認(ユーザー登録画面)

terminal
rails s


ユーザー新規登録画面に表示されるパンくずリスト

ユーザー詳細画面に表示するパンくずリストを設定

config/breadcrumbs.rb
  ---省略---
 # 下記を追記
+ crumb :user_show do |user|
+   link "#{user.name}さんの詳細", user_path(user)
+   parent :root
+ end

パンくずリストの設定を表示させる(users/show.html.erb)

app/views/users/show.html.erb
 # 下記を追加 @userに注意
+ <% breadcrumb :user_show, @user %>

  <p id="notice"><%= notice %></p>

  <p>
    <strong>Name:</strong>
    <%= @user.name %>
  </p>

  <%= link_to 'Edit', edit_user_path(@user) %> |
  <%= link_to 'Back', users_path %>

サーバーを起動してパンくずリストが表示されることを確認(ユーザー詳細画面)

terminal
rails s


ユーザー詳細画面に表示されるパンくずリスト

参考サイト・資料

Pikawaka:【Rails】 gretelを使ってパンくずリストを作成しよう
gretel公式ドキュメント

0
0
1

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
0