views:

27

answers:

1

Given a Rails 3 App with a menu like:

<ul>
 <li>Home</li>
 <li>Books</li>
 <li>Pages</li>
</ul>

What is a smart way in Rails to have the app know the breadcrumb,,, or when to make one of the LIs show as:

 <li class="active">Books</li>

thx

+1  A: 

I'm not sure if I will provide you with a smart way but better something than nothing...

If your menu has some links - it is not in your example but I suppose that real menu should have links, not just the items. For example something like this in HAML: (I'm using HAML as writing ERB in text area is pure hell)

%ul
  %li= link_to "Home", :controller => "home"
  %li= link_to "Books", :controller => "books"
  %li= link_to "Pages", :controller => "pages"

Then this helper (pasted from my project) should come handy:

#
# Shows link with style "current" in case when the target controller is same as 
# current
# beware: this helper has some limitation - it only accepts hash as URL parameter
#
def menu_link_to(title, url, html_options = {})
  unless url.is_a?(Hash) and url[:controller]
    raise "URL parameter has to be Hash and :controller has to be specified"
  end

  if url[:controller] == controller.controller_path
    html_options[:class] = "current"
  end

  link_to(title, url, html_options)
end

With this helper you can replace your "link_to" in the code above with "menu_link_to" and that's it!

pawien