Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply an 'active' class to my navigation based on the current_page in a DRY way? - Rails 3

So in my application.html.erb I have my navigational structure that looks something like this:

<div id="navigation">
            <ul class="pills">
                    <% if current_page?(:controller => 'welcome', :action => 'index') %>
                        <li><%= link_to "Profile", vanity_path(:vname => current_user.username) %></li>
                        <li><%= link_to "Settings", settings_path %></li>
                        <li><%= link_to "Sign Out", signout_path %></li>
                    <% elsif !current_page?(:controller => 'welcome', :action => 'index') %>
                        <li><%= link_to "Home", root_path %></li>
                        <li><%= link_to "Profile", vanity_path(:vname => current_user.username) %></li>
                        <li><%= link_to "Settings", settings_path %></li>
                        <li><%= link_to "Sign Out", signout_path %></li>              
                    <% end %>
            </ul>
        </div>

However, what I would like to do, is once they are on any of the pages in the navigation, it applies a class active to the respective link.

So for instance, if the user is on mydomain.com/johnbrown which is the Profile link, the rails helper would look something like this:

link_to "Profile", vanity_path(:vname => current_user.username), :class => "active".

But how do I do that in a programmatic way, so I am not duplicating content? i.e. how do I get that functionality for all the pages in my navigation and write it as DRY as possible?

Thanks.

like image 201
marcamillion Avatar asked Oct 23 '25 05:10

marcamillion


1 Answers

This is a really great question. I've never really been happy with the solutions I've seen or come up with. Maybe we can get one together here.

Here is what I've tried in the past

I've made a helper that returns a hash with :class defined since I use HAML

def active_tab(path)
  request.path.match(/^#{path}/) ? { :class => 'active' } : {}
end

ex usage:

= link_to "Dashboard", dashboard_path, active_tab("#{dashboard_path}$")

Or an alternative along the same lines

def active_class(path)
  request.path =~ /#{path}/ ? 'active' : nil
end

ex usage:

= link_to 'Presentations', admin_presentations_path, :class => "#{active_class('presentations')}"

I would love to see some other suggestions on this.

like image 128
Matt Polito Avatar answered Oct 24 '25 20:10

Matt Polito