Rail3 - 智能显示菜单和方式添加活动样式类?

时间:2010-09-26 22:52:25

标签: ruby-on-rails ruby-on-rails-3

给出Rails 3应用程序,其菜单如下:

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

Rails中有什么聪明的方法让应用知道面包屑,,或何时将其中一个LI显示为:

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

THX

2 个答案:

答案 0 :(得分:2)

我不确定我是否会为你提供一个聪明的方式,但更好的东西比什么都没有......

如果您的菜单中有一些链接 - 它不在您的示例中,但我认为真正的菜单应该包含链接,而不仅仅是项目。例如HAML中的这样的东西:(我使用HAML在文本区域写ERB是纯粹的地狱)

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

然后这个助手(从我的项目中粘贴)应该会派上用场:

#
# 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

使用此帮助程序,您可以使用“menu_link_to”替换上面代码中的“link_to”,就是这样!

答案 1 :(得分:1)

Radek Paviensky帮手的修改版本更简单,更类似于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