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

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

    Create a method in ApplicationHelper as below.

    def active controllers, action_names = nil
      class_name = controllers.split(",").any? { |c| controller.controller_name == c.strip } ? "active" : ""
      if class_name.present? && action_names.present?
        return action_names.split(",").any? { |an| controller.action_name == an.strip } ? "active" : ""
      end
      class_name
    end
    

    Now use it in view as below use cases.

    1. For all action of any specific controller

  • ....
  • 2. For all action of many controllers (with comma seperated)

  • ....
  • 3. For specific action of any specific controller

  • ....
  • 4. For specific action of many controllers (with comma seperated)

  • ....
  • 5. For some specific actions of any specific controller

  • ....
  • 6. For some specific actions of many controllers (with comma seperated)

  • ....
  • Hope it helps

提交回复
热议问题