Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For the following code:

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

How do I apply a css class current using the current_page?‎ helper method?

Or if some other better way is available?

like image 837
Jacob Avatar asked Dec 18 '11 15:12

Jacob


3 Answers

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" %> 
like image 175
Michael van Rooijen Avatar answered Sep 20 '22 19:09

Michael van Rooijen


In my case I have a lot of name spaced controllers, that is why I like to show if the current view also is in the Menu Path, I had use the solution of Michael van Rooijen and then I customize for my case.

Helper

def cp(path)
  "current" if request.url.include?(path)
end

View

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

Now if my menu bar is /users and my current page is /users/10/post also the link /users is set with "current" class

like image 30
rderoldan1 Avatar answered Sep 20 '22 19:09

rderoldan1


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!

like image 28
Eric Boehs Avatar answered Sep 23 '22 19:09

Eric Boehs