Best way to highlight current page in Rails 3? — apply a css class to links conditionally

后端 未结 8 1766
野趣味
野趣味 2020-12-04 14:25

For the following code:

<%= link_to \"Some Page\", some_path %>

How do I apply a css class current using the

8条回答
  •  清歌不尽
    2020-12-04 14:48

    I branched off of Michael's answer and tweaked the helper:

    def active_class?(*paths)
      active = false
      paths.each { |path| active ||= current_page?(path) }
      active ? 'active' : nil
    end
    

    Here's how you'd use it:

    <%= link_to "Bookings", bookings_path, class: active_class?(bookings_path) %>
    

    You can pass multiple paths to it in case you have a tab which could be rendered by multiple views:

    <%= content_tag :li, class: active_class?(bookings_path, action: 'new') %>
    

    And the great thing about this is if the conditions are false, it will insert nil. Why is this good? Well, if you provide class with nil it won't include the class attribute on the tag at all. Bonus!

提交回复
热议问题