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

后端 未结 8 1768
野趣味
野趣味 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 15:03

    In the interest of not having to repeat your self too much by having to check current_page inside the link_to method all the time, here's a custom helper that you can use (put this in app/views/helpers/application_helpers.rb

    def link_to_active_class(name, active_class_names, options = {}, html_options = {}, &block)
      html_options[:class] = html_options[:class].to_s + active_class_names if current_page?(options.to_s)
      link_to name, options, html_options, &block
    end
    

    Example usage:

    <%= link_to_active_class('Dashboard', 'bright_blue', dashboard_path, class: 'link_decor')

    if you are on http://example.com/dashboard, then it should return:

    
    

    Regards.

提交回复
热议问题