开发者

Rail3 - Smart way to Display Menu & add an Active Style Class?

开发者 https://www.devze.com 2023-01-17 21:41 出处:网络
Given a Rails 3 App with a menu like: <ul> <li>Home</li> <li>Books</li>

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 i开发者_JAVA百科n Rails to have the app know the breadcrumb,,, or when to make one of the LIs show as:

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

thx


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!


An modified version of Radek Paviensky's helper is a tad simpler and more similar to link_to.

  # Shows link with style "current" in case when the target controller is same as 
  # current.
  def menu_link_to(title, options = {}, html_options = {})
    if current_page?(options)
      html_options[:class] ||= []
      html_options[:class] << "active" # @TODO catch cases where the class is passed as string instead of array.
    end

    link_to(title, options, html_options)
  end
0

精彩评论

暂无评论...
验证码 换一张
取 消