How to get Twitter-Bootstrap navigation to show active link?

前端 未结 22 2126
一整个雨季
一整个雨季 2020-11-27 09:31

I\'m not understanding how Twitter Bootstrap does active links for the navigation. If I have a regular navigation like this (with ruby on rails linking):

<         


        
22条回答
  •  再見小時候
    2020-11-27 10:20

    I used a helper to implement this in the style of Rails' form helpers.

    In a helper (e.g. app/helpers/ApplicationHelper.rb):

    def nav_bar
      content_tag(:ul, class: "nav navbar-nav") do
        yield
      end
    end
    
    def nav_link(text, path)
      options = current_page?(path) ? { class: "active" } : {}
      content_tag(:li, options) do
        link_to text, path
      end
    end
    

    Then, in a view (e.g. app/views/layouts/application.html.erb):

    <%= nav_bar do %>
      <%= nav_link 'Home', root_path %>
      <%= nav_link 'Posts', posts_path %>
      <%= nav_link 'Users', users_path %>
    <% end %>
    

    This example produces (when on the 'users' page):

    
    

提交回复
热议问题