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

后端 未结 8 1629
野趣味
野趣味 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:05

    I think if would be good idea if you generate whole link_to from your helper method. Why to repeat the same code ( :-) DRY principle)

    def create_link(text, path)
      class_name = current_page?(path) ? 'current' : 'any_other_class'
    
      link_to text, path, class: class_name
    end
    

    Now you can use like:

    <%= create_link 'xyz', any_path %> (in views) which would render as <a href="/any" class="current">xyz</a>

    Hope it helps!

    0 讨论(0)
  • 2020-12-04 15:06

    In app/helpers/application_helper.rb

    def cp(path)
      "current" if current_page?(path)
    end
    

    In your views:

    <%= link_to "All Posts", posts_path, class: cp(posts_path) %>
    

    Basically write a simple wrapper around it. Additionally you could extend the method to allow additional classes to be applied by adding arguments. Keeps the views concise/dry. Or, without extending the method, you could just do simple String interpolation like so to add additional classes:

    <%= link_to "All Posts", posts_path, class: "#{cp(posts_path)} additional_class" %>
    
    0 讨论(0)
提交回复
热议问题