Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mark a link in a layout menu as "active" in rails?

I have a ul filled with links in my layout/application.html.erb and want the current location link be marked with class="active".

Now I'm using:

<%= link_to 'About Us', { :controller => 'aboutus' }, :class => "menu#{' active' if params[:controller] == 'aboutus'}" %>

But it looks pretty nasty to me.

Anyone has a better idea?

like image 366
Erik Escobedo Avatar asked Dec 02 '22 05:12

Erik Escobedo


2 Answers

The link_to_unless_current method doesn't actually create a link, nor does it add a class of active. If you'd still like to do that, you can use the current_page method to check if the current page matches the route you specified:

<ul id="main_nav">
  <li><%= link_to "Search", search_path, :class => ('active' if current_page?(search_path)) %></li>
</ul>

Or if you'd like to add the class on the wrapping element:

<li class="<%= 'active' if current_page?(search_path) %>">
  <%= link_to "Search", search_path %>
</li>
like image 122
Andrew Avatar answered Dec 04 '22 04:12

Andrew


You can use the helper method similar to link_to

its called "link_to_unless_current".

http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html ( find the details here )

HTH

like image 22
Rishav Rastogi Avatar answered Dec 04 '22 05:12

Rishav Rastogi