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

后端 未结 24 1796
天涯浪人
天涯浪人 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:39

    This version is based on @Skilldrick's one but allows you to add html content.

    Thus, you can do:

    nav_link "A Page", a_page_path

    but also:

    nav_link a_page_path do
      A Page
    end
    

    or any other html content (you can add an icon for instance).

    Here the helper is:

      def nav_link(name = nil, options = nil, html_options = nil, &block)
        html_options, options, name = options, name, block if block_given?
        options ||= {}
    
        html_options = convert_options_to_data_attributes(options, html_options)
    
        url = url_for(options)
        html_options['href'] ||= url
    
        class_name = current_page?(url) ? 'current' : ''
        content_tag(:li, :class => class_name) do  
          content_tag(:a, name || url, html_options, &block)
        end
      end
    

提交回复
热议问题