Ruby on Rails highlight current link on navigation

2019-06-17 02:30发布

问题:

Can anyone tell me how to highlight (with color) the current link on a navigation bar, using css? I don't 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>

回答1:

There are a few approaches to this, but if you're after a simple one, 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 multiple pages you want to split, but for this basic example it should be ok.



回答2:

The first approach is to handle current controller_name and action_name to detect what page you are on. It's good, but it adds a bit of server-side to client-specific template. The rails helper uses that way is link_to_unless_current. Minimum usage of JS. See an example here

The second is to parse $(location) and directly add a certain class to the selected navigation item to highlight it.

The third (depends on an object) is to build a JS object with current state of entity and add methods to add a class to an active nav. Then you can instantiate this JS class, passing on the object and keeping the logic encapsulated.



回答3:

Something like this would work for you. Of course you'd have to tweak it to your purposes, maybe get more sophisticated with the match (currently this would only match paths, as you have in your example).

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

Better still, you'd define a "current" class somewhere, then simply add it:

/* in some stylesheet */
#navigation li.current { background-color: #ff0; }

/* then the js */
$("#navigation a[href="+window.location.pathname+"]")
  .closest('li')
    .addClass('current');