Best way to add “current” class to nav in Rails 3

后端 未结 24 1771
天涯浪人
天涯浪人 2020-11-29 15:05

I have some static pages in a navigation menu. I want to add a class like \"current\" to the item which is currently displaying.

The way I am doing so is to add tons

24条回答
  •  情歌与酒
    2020-11-29 15:33

    I have a more succinct version of nav_link that works exactly like link_to, but is customized to output a wrapping li tag.

    Put the following in your application_helper.rb

    def nav_link(*args, &block)
        if block_given?
          options      = args.first || {}
          html_options = args.second
          nav_link(capture(&block), options, html_options)
        else
          name         = args[0]
          options      = args[1] || {}
          html_options = args[2]
    
          html_options = convert_options_to_data_attributes(options, html_options)
          url = url_for(options)
    
          class_name = current_page?(url) ? 'active' : nil
    
          href = html_options['href']
          tag_options = tag_options(html_options)
    
          href_attr = "href=\"#{ERB::Util.html_escape(url)}\"" unless href
          "
  • #{ERB::Util.html_escape(name || url)}
  • ".html_safe end end

    If you look at the above code and compare it to the link_to code in url_helper.rb, the only difference is that it checks if the url is the current page, and adds the class "active" to a wrapping li tag. This is because I'm using the nav_link helper with Twitter Bootstrap's nav component which prefers links to be wrapped inside li tags and the "active" class applied to the outer li.

    The nice thing about the above code is that it allows you to pass in a block into the function, just like you can do with link_to.

    For example, a bootstrap nav list with icons would look like:

    Slim:

    ul.nav.nav-list
      =nav_link root_path do
        i.icon-home
        |  Home
      =nav_link "#" do
        i.icon-user
        |  Users
    

    Output:

    
    

    In addition, just like the link_to helper, you can pass in HTML options into nav_link, which will be applied to the a tag.

    An example of passing in a title for the anchor:

    Slim:

    ul.nav.nav-list
      =nav_link root_path, title:"Home" do
        i.icon-home
        |  Home
      =nav_link "#", title:"Users" do
        i.icon-user
        |  Users
    

    Output:

    
    

提交回复
热议问题