Highlight tab in menu

前端 未结 5 1767
甜味超标
甜味超标 2020-12-28 18:51

I have a menu which is a ul

Home | Calendar | Settings

I want to highlight (via a css class) the selected tab in the menu.

Some lin

相关标签:
5条回答
  • 2020-12-28 19:23

    Update to @ahmy's answer for Rails 3.2:

    def menu_list_item(*args, &block)
      url = args[1]
      mapping =  Rails.application.routes.recognize_path(url)   
    
      li_class = 'active' if mapping[:controller] == controller.controller_path
      content_tag :li, :class => li_class do
        link_to *args, &block
      end
    end
    

    i.e. Rails.application.routes.recognize_path instead of ActionController::Routing::Routes.recognize_path.

    0 讨论(0)
  • 2020-12-28 19:29

    I settled on this solution which I like a lot:

    In the helper

    def active_if(options)
      if params.merge(options) == params
        'nav-active'
      end
    end
    

    And in the view define what makes the route unique:

    <%= link_to 'Home', root_path, class: active_if(action: 'home') %>
    <%= link_to 'Aricles', articles_path, class: active_if(controller: 'articles') %>
    
    0 讨论(0)
  • 2020-12-28 19:40

    In your helper file:

    def is_active?(page_name)
      "active" if params[:action] == page_name
    end
    

    In the template file:

    link_to 'Home', '/', :class => is_active?("index")
    link_to 'About', '/about', :class => is_active?("about")
    link_to 'contact', '/contact', :class => is_active?("contact")
    

    I found this on: http://juliocapote.com/post/52081481/highlight-link-based-on-current-page-in-rails

    0 讨论(0)
  • 2020-12-28 19:43

    I have the same problem and end up creating helper. basicly it replace the link_to url helper so it wrap the link with li and add class "menu_selected" if the current controller matches the link controller

    usage sample

    <%= menu_link_to "Home", home_path %>
    
    
    def menu_link_to(*args, &block)
      url = args[1]
      mapping =  ActionController::Routing::Routes.recognize_path(url)   
    
      class_property = "menu_selected" if mapping[:controller] == controller.controller_path
      content_tag :li, :class => class_property do
        link_to *args, &block
      end
    end
    
    
    0 讨论(0)
  • 2020-12-28 19:44

    The simplest way would be to check which controller is being used. I made up controller names, so of course you would replace 'home', 'calendar', and 'settings' with the correct names.

    <ul>
      <li class="<%= "highlighted" if params[:controller] == "home" %>">Home</li>
      <li class="<%= "highlighted" if params[:controller] == "calendar" %>">Calendar</li>
      <li class="<%= "highlighted" if params[:controller] == "settings" %>">Settings</li>
    </ul>
    
    0 讨论(0)
提交回复
热议问题