Breadcrumbs in Ruby on Rails
Breadcrumbs menu are a recurrent pattern in most Rails applications. To solve this issue, I created and released a plugin called breadcrumbs_on_rails.
You define your breadcrumbs in the controller
class MyController add_breadcrumb "home", root_path add_breadcrumb "my", my_path def index # ... add_breadcrumb "index", index_path endend
and you render them in your view.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>untitled</title></head><body> <%= render_breadcrumbs %></body></html>
Even if you don't want to use a plugin, I encourage you to give it a look. It's open source and you can grab some idea for your app.
I made a gem named Gretel that is a Ruby on Rails plugin for creating breadcrumbs. The breadcrumbs are configured in a separate configuration file and selected in the view.
Example config/breadcrumbs.rb
:
crumb :root do link "Home", root_pathendcrumb :projects do link "Projects", projects_pathendcrumb :project do |project| link project.name, project_path(project) parent :projectsendcrumb :project_issues do |project| link "Issues", project_issues_path(project) parent :project, projectendcrumb :issue do |issue| link issue.name, issue_path(issue) parent :project_issues, issue.projectend
In your view:
<% breadcrumb :issue, @issue %>
In your app/views/layouts/application.html.erb:
<%= breadcrumbs pretext: "You are here: " %>
This is mostly a matter of opinion, but anyway:
- I would not want that much logic in a view. We've probably all done it, but it gets messy quickly.
- The code is not safe against future changes that affect the depth of the tree.
- Instead of linked variables
*_name
and*_link
, I'd suggest using proper objects anyway, with somelink_to
functionality.
You might find Episode 162 of Railscasts of interest for a nice solution that gets by with
<% for page in @page.ancestors.reverse %> <%= link_to h(page.name), page %> ><% end %>