--People who want to implement breadcrumb trails in Rails. --People who forgot how to use it. ――It is for beginners. The content also explains the rudimentary part.
Breadcrumb trail. The story of Hansel and Gretel. You can see the path you have taken by dropping breadcrumbs.
Click here for gretel's github
Gemfile
gem 'gretel'
After bundle install
, generate the necessary files.
$ bundle install
$ rails g gretel:install
It is OK if the file is generated as follows.
Running via Spring preloader in process 6675
create config/breadcrumbs.rb
This is the contents.
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
#
#
#Omitted below
#
#
#
The file breadcrumbs.rb
mentioned earlier is a file that can be set to drop bread crumbs.
For example
Home> Category
If you want to remove breadcrumbs like
breadcrumb.rb
crumb :root do
link "Home", root_path
end
crumb :articles do
link "List of articles", articles_path #パスは該当ページのパスを書く(ここではList of articles)
parent :root
end
Since we want the page before the category to be Home, parent specifies : root
.
All you have to do is output it in View.
erb:application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Bread crumb app</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<%= breadcrumbs separator: " › " %> #Add here
<%= yield %>
</body>
</html>
erb:articles/index.html.erb
<% breadcrumb :articles %>
with this
Home> Article List
The breadcrumb trail is ready.
Home> Article List> [Article Title]
If you want to do something like this, you need to devise a little.
You have to send the data from View to breadcrumb.rb
as shown below.
This time, I want to output the title of the article as breadcrumbs, so I will pass the data by specifying @article
as the second argument.
erb:articles/show.html.erb
<% breadcrumb :article_show, @article %>
breadcrumb.rb
crumb :root do
link "Home", root_path
end
crumb :articles do
link "List of articles", articles_path #パスは該当ページのパスを書く(ここではList of articles)
parent :root
end
crumb :article_show do |article| #Received here
link article.title, article_path(article) #<Character string to display>、<Article detail path>
parent :articles #Set parent
end
Home> Article list> I made a breadcrumb trail
If you want to output the creation date and time,
breadcrumbs.rb
crumb :article_show do |article|
link article.created_at, article_path(article) #Change (title=> created_at)
parent :articles
end
If you change it to, it's OK.
Recommended Posts