I want to make links on current URL with different CSS.
Ex: If I'm in "/photos", I want to have the Photos link to be in a different color (as active).
Isnt there a method in Rails to make this?
Thanks
I want to make links on current URL with different CSS.
Ex: If I'm in "/photos", I want to have the Photos link to be in a different color (as active).
Isnt there a method in Rails to make this?
Thanks
You can test the params[:controller]
to do so:
%ul
%li= link_to 'Users', users_path, class: (UsersController.controller_name == params[:controller]) ? 'active' : 'not_active'
%li= link_to 'Photos', photos_path, class: (PhotosController.controller_name == params[:controller]) ? 'active' : 'not_active'
But this seems to be heavy and annoying to copy/paste everything for each link... -> Let's make a helper!
# application_helper.rb
def active_if_in_controller?(*controllers)
is_in_controller = controllers.flatten.map(&:to_s).include? controller_name
is_in_controller ? 'active' : 'not_active'
end
# usage in views:
%ul
%li= link_to 'Users', users_path, class: active_if_in_controller?(UsersController.controller_name)
%li= link_to 'Settings', settings_path, class: active_if_in_controller?(Settings::UsersController, Settings::PhotosController)
You can add a class to the body tag representing your current controller name in application.html.erb
:
<body class="<%= controller.controller_name %>">
That code will result this on "/photos":
<body class="photos">
In your css file add something like this:
body.photos a.active {
color: red
}
The creation of the links (Rails) will have to add a specific class to the link of the current page. e.g. "active". It should look something like this:
<ul>
<li><a href="">link1</a></li>
<li><a href="" class="active">current link</a></li>
<li><a href="">link3</a></li>
</ul>
Now you should style accordingly the "active" class. Example:
a.active {
color: #fff;
}
You should do this using javascript. The reason for this is simple. When you want to do this serverside you need to touch the link_to
method which isnt't for beginners. You can do this with jQuery easy:
$("a[href*='" + location.pathname + "']").addClass("current_link");
Then in css:
.current_link {
# highlight the link in some kind
}
// You can also use the canonial link element when you have many urls that match one page for SEO reasons. Then you can also use this element to highlight the correct link:
$("a[href*='" + $('link[rel=canonical]').attr('href') + "']").addClass("current_link");
THis will not work when you use get parameters but for that case you can cut away all params included in the url if that works for you can find an explaination here.