Created
August 26, 2009 14:14
-
-
Save henrik/175523 to your computer and use it in GitHub Desktop.
Simple breadcrumb trail for Rails. MIT license. Will likely spec and pluginize later.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
You are here: | |
<%= trail.to_html(response) %> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationController < ActionController::Base | |
before_filter :trail | |
def self.trail(&block) | |
# Controller-level trails become filters so they run inside the | |
# request/response cycle, where internationalization etc works. | |
# instance_exec means you can use path helpers. | |
before_filter {|controller| controller.instance_exec(controller.send(:trail), &block) } | |
end | |
trail {|t| t << ['Home', '/'] } | |
protected | |
def trail | |
@breadcrumb_trail ||= BreadcrumbTrail.new | |
end | |
helper_method :trail | |
class BreadcrumbTrail | |
def initialize | |
@crumbs = [] | |
end | |
def <<(crumb) | |
@crumbs << crumb | |
end | |
def append(crumbs) | |
@crumbs += crumbs | |
end | |
def to_html(response) | |
template = response.template | |
@crumbs.map { |crumb| | |
text, url = Array(crumb) | |
last_crumb = @crumbs.last | |
template.instance_eval { | |
link_to_unless((crumb == last_crumb || url.blank?), h(text), url) {|text| content_tag(:span, text) } | |
} | |
}.join(" > ") | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ItemsController < ApplicationController | |
trail {|t| t << ['Items', '/items'] } | |
def show | |
trail << ['Specific item from controller', '/items/123'] | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<% | |
trail << ['Specific item from view', '/items/123'] | |
# Note that since layouts are rendered after their child template, | |
# trails appended in a layout will currently come after those | |
# appended in the child templates. | |
%> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment