Welcome to Delicate template
Header
Just another WordPress site
Header

Rails breadcrumbs

July 25th, 2008 | Posted by Michaël in ICT | Ruby On Rails | Web Development

As I was working on my new project, I was in need of a some breadcrumbs to implement on my site. Since I hate doing the same task over and over again, I looked for a ready to deploy plugin. After some googling, I quicly realized that a standard way of creating breadcrumbs is virtualy impossible.

The way of creating your bread trail can depend on diffrent situations and can change from project to project. I just think that this way of generating your bread trail I realy neat, and would fit about 80% of most projects. The application controller code can even serve as a starting point for generating the trail dynamicaly.

Start and put the following in your application_controller.rb file:

 protected
   def add_breadcrumb name, url = ''
     @breadcrumbs ||= []
     url = eval(url) if url =~ /_path|_url/
     @breadcrumbs << [name, url]
   end  
 
   def self.add_breadcrumb name, url, options = {}
     before_filter options do |controller|
       controller.send(:add_breadcrumb, name, url)
     end
   end

Theses methods will be used in other controllers to build up the trail. Offcourse, every trail starts with the Home page. So it would be stupid to repeat that in every controller. The author of the blog post suggested to put

add_breadcrumb 'Home', '/'

in the top of your application controller, but that gave some problems for me. So what I did is, since I use the initialize method in my application method, is just to put the code right there.

So how do you continue to build up the trail you might think now? Just open an arbitrary controller and add something similar to the top:

  add_breadcrumb 'Resource', '/resources'
  add_breadcrumb 'List', '', :only => [:index, :destroy]
  add_breadcrumb 'Create a new resource', '', :only => [:new, :create]
  add_breadcrumb 'Edit a resource', '', :only => [:edit, :update]

This way, all your crumb entries are grouped at the top of the controller. But if you need to customize, you can just add an entry in your action aswell.

Now, you would like to view your breadcrumbs. Go to the right view (most likely you default layout page) and add the following code:

<%= @breadcrumbs.map { |txt, path| "
  • #{link_to_unless(path.blank?, h(txt), path)}
  • " } %>

    Source: http://szeryf.wordpress.com/2008/06/13/easy-and-flexible-breadcrumbs-for-rails/

    You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

    2 Responses



    Leave a Reply

    Your email address will not be published. Required fields are marked *

    *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">