Does Ruby on Rails highlight the current link in the navigation bar?

Can someone tell me how to highlight (with color) the current link in the navigation bar using css? I do not want to use the controller option. Here is the code from shared / menu.html.erb:

<div id = "navigation"> <ul> <li id="menu"><%=link_to "Menu", menus_path, :class => "menunav"%></li> <li id="drink"><%=link_to " Drinks", drinks_path, :class => "drinknav"%> </li> </ul> </div> 
+7
source share
3 answers

There are several approaches to this, but if you are after a simple, I suggest adding a class to your body.

 <body class="<%= params[:controller] %>_controller"> ... </body> 

Then in your css you can do the following.

 body.menus_controller #navigation a.menunav, body.drinks_controller #navigation a.drinknav { background-color : yellow color : blue } 

This can get complicated if you have several pages that you want to split, but for this basic example this should be good.

+3
source

The first approach is to process the current controller_name and activity_name to determine which page you are on. This is good, but it adds a little server-side for the client template. The rails helper uses this link_to_unless_current method. Minimal use of JS. Example here

Secondly, you need to analyze $ (location) and directly add a specific class to the selected navigation element to highlight it.

The third (depending on the object) is to create a JS object with the current state of the entity and add methods to add the class to the active nav. You can then instantiate this JS class, pass the object, and save the encapsulated logic.

+7
source

Something like this will work for you. Of course, you will need to configure it for your own purposes, perhaps to get a more complex combination (currently this will only match the path, as in your example).

 $("#navigation a[href="+window.location.pathname+"]") .closest('li') .css('background-color', '#ff0'); 

Even better, you would define the β€œcurrent” class somewhere, and then just add it:

 /* in some stylesheet */ #navigation li.current { background-color: #ff0; } /* then the js */ $("#navigation a[href="+window.location.pathname+"]") .closest('li') .addClass('current'); 
+4
source

All Articles