Breadcrumbs On Rails
BreadcrumbsOnRails is a simple Ruby on Rails plugin for creating and managing a breadcrumb navigation for a Rails project. It provides helpers for creating navigation elements with a flexible interface.
Requirements
- Rails 4 or Rails 5
For older versions of Ruby or Ruby on Rails, see the CHANGELOG.
Installation
Add this line to your application's Gemfile
:
gem "breadcrumbs_on_rails"
And then execute bundle
to install the dependencies:
$ bundle
Use Bundler and the :git
option if you want to grab the latest version from the Git repository.
Usage
Creating a breadcrumb navigation menu in your Rails app using BreadcrumbsOnRails is really straightforward.
In your controller, call add_breadcrumb
to push a new element on the breadcrumb stack. add_breadcrumb
requires two arguments: the name of the breadcrumb and the target path.
class MyController
"home", :root_path
"my", :my_path
def index
# ...
"index", index_path
end
end
See the section "Breadcrumb Element" for more details about name and target class types.
The third, optional argument is a Hash of options to customize the breadcrumb link.
class MyController
def index
"index", index_path, :title => "Back to the Index"
end
end
In your view, you can render the breadcrumb menu with the render_breadcrumbs
helper.
<!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>
render_breadcrumbs
understands a limited set of options. For example, you can pass change the default separator with the :separator
option.
<body>
<%= render_breadcrumbs :separator => ' / ' %>
</body>
Current possible options are:
:separator
:tag
To use with Bootstrap you might use the following:
<body>
<ol class="breadcrumb">
<%= render_breadcrumbs :tag => :li, :separator => "" %>
</ol>
</body>
More complex customizations require a custom Builder
.
HTML Escaping
The text of the breadcrumb is html-escaped by default unless it is a SafeBuffer, to prevent XSS attacks.
class MyController
"This is the <b>Main</b> page".html_safe
def profile
"#{@user_name} Profile", users_profile
end
end
In this case, if @user_name
is "