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

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

    To build off @Skilldrick 's answer...

    If you add this code to application.js it will make sure that any dropdown menus with active children will also be marked as active...

    $('.active').closest('li.dropdown').addClass('active');
    

    To recap supportive code > Add a helper called nav_link:

    def nav_link_to(link_text, link_path)
      class_name = current_page?(link_path) ? 'active' : ''
    
      content_tag(:li, :class => class_name) do
        link_to link_text, link_path
      end
    end
    

    used like:

    nav_link_to 'Home', root_path
    

    which will produce HTML like

  • Home
提交回复
热议问题