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?
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?
I tried to combine a couple of the mentioned techniques with my own needs.
Basically it allows you to use it like this:
create_nav_item("profile", profile_path)
which will result in:<li><a href="/profile" data-hover="Profile">Profile</a></li>
,or
<li class="current"><a href="/profile" data-hover="Profile">Profile</a></li>
if this is the current page.I didn't use
request.url.include?(path)
since it will also always highlight the "Home" button, and I couldn't think of a work around by far.In app/helpers/application_helper.rb
In your views:
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:
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)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!
I'd do it this way :
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
View
Now if my menu bar is /users and my current page is /users/10/post also the link /users is set with "current" class
I branched off of Michael's answer and tweaked the helper:
Here's how you'd use it:
You can pass multiple paths to it in case you have a tab which could be rendered by multiple views:
And the great thing about this is if the conditions are
false
, it will insertnil
. Why is this good? Well, if you provideclass
withnil
it won't include the class attribute on the tag at all. Bonus!