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

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

    The way I've done it is to add a helper function in the application_helper

    def current_class?(test_path)
      return 'current' if request.request_uri == test_path
      ''
    end
    

    Then in the nav,

    <%= link_to 'Home', root_path, :class => current_class?(root_path) %>
    

    This tests the link path against the current page uri and returns either your current class or an empty string.

    I've not tested this thoroughly and I'm very new to RoR (moving over after a decade with PHP) so if this has a major flaw I'd love to hear it.

    At least this way you only need 1 helper function and a simple call in each link.

提交回复
热议问题