Easy breadcrumbs for Rails apps.
-
Include
Croutons::Controller
in yourApplicationController
.This will make a
#breadcrumbs
helper available in your layouts and views. -
Call the
#breadcrumbs
helper in your layouts or views. -
Define a
BreadcrumbTrail
class, which inherits fromCroutons::BreadcrumbTrail
. -
Define missing methods on the
BreadcrumbTrail
class.For example, for the
admin/locations/index.html.erb
view you would define an#admin_locations_index
method.In these methods, you build up a breadcrumb trail by calling
#breadcrumb
with a label and an optional URL. You can also call previously defined methods to build on existing trails. View assigns (i.e. the controller instance variables) are available via the#objects
method which returns aHash
. Rails route helpers are also available inside this class.
Please see the example below for further reference.
-
Instead of defining a
BreadcrumbTrail
class you can use an object of your own that responds to#breadcrumbs
.To do this, override the private
#breadcrumb_trail
method in the controller where you includedCroutons::Controller
, to return the object you want to use.The
#breadcrumbs
method is passed two parameters: onetemplate_identifier
String
and oneobjects
Hash
. The#breadcrumbs
method should return anArray
ofCroutons::Breadcrumb
s. -
Override the view used to render breadcrumbs.
To do this, create a view called
breadcrumbs/_breadcrumbs.html.erb
.In this view, an
Array
ofCroutons::Breadcrumb
s is assigned to the local variablebreadcrumbs
. TheseCroutons::Breadcrumb
s have two public attributes:#label
and#url
. The#url
attribute is optional. To check whether theCroutons::Breadcrumb
has a#url
or not (i.e. should be rendered as a link or not), check whether the#link?
method returnstrue
orfalse
.
class ApplicationController < ActionController::Base
include Croutons::Controller
end
class PostsController < ApplicationController
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
end
<!DOCTYPE html>
<html>
<head>
<title>My blog</title>
</head>
<body>
<%= breadcrumbs %>
<%= yield %>
</body>
</html>
class BreadcrumbTrail < Croutons::BreadcrumbTrail
def posts_index
breadcrumb("Posts", posts_path)
end
def posts_show
posts_index
breadcrumb(objects[:post].title, post_path(objects[:post])
end
end
Croutons is Copyright © 2014 Calle Erlandsson, George Brocklehurst, and thoughtbot. It is free software, and may be redistributed under the terms specified in the LICENSE file.