Menu

Back Home

Active state for link_to == active_link_to. A solution for building navigation systems in Rails.

I have a question for you. How do you deal with the logic of setting links as active in your navs?

Actually, I don’t want to know. It’s probably awful. I might have a pretty good solution for you. Let’s take a look at a very simple nav. These examples all use HAML:

[ccN_ruby]
%ul
%li= link_to ‘Home’, home_path
%li= link_to ‘Puppies’, puppies_path
%li= link_to ‘Kittens’, kittens_path
%li= link_to ‘Froggies’, froggies_path
[/ccN_ruby]

Right, that’s great. But how do I insert logic as to what link gets marked as active? To begin, let’s quickly install this random gem:
[ccN_bash]
sudo gem install active_link_to
[/ccN_bash]

And then change our nav a bit:
[ccN_ruby]
%ul
%li= active_link_to ‘Home’, home_path
%li= active_link_to ‘Puppies’, puppies_path
%li= active_link_to ‘Kittens’, kittens_path
%li= active_link_to ‘Froggies’, froggies_path
[/ccN_ruby]

And that’s pretty much it.

So, for example, if you navigate to /kittens/1-my-fluffy-kitten navigation link for ‘Kittens’ will have ‘active’ class attached to it. It’s almost like magic.

You probably noticed that ‘Home’ is highlighted as well. It happened because whatever URL you are currently on is a child of the home_path. I guess we want to mark it as active only if we find ourselves on the home page and not anywhere else. We can fix this:

[ccN_ruby]
%ul
%li= active_link_to ‘Home’, home_path, :active => {:when => :self_only}
%li= active_link_to ‘Puppies’, puppies_path
%li= active_link_to ‘Kittens’, kittens_path
%li= active_link_to ‘Froggies’, froggies_path
[/ccN_ruby]

Hey, wanna render a sub nav when you find yourself browsing /puppies or any page under that URL? It’s just sooo easy:

[ccN_ruby]
%ul
%li= active_link_to ‘Home’, home_path, :active => {:when => :self_only}
%li
= active_link_to ‘Puppies’, puppies_path
– if is_active_link?(puppies_path)
%ul
%li= active_link_to ‘Big’, big_puppies_path
%li= active_link_to ‘Small’, small_puppies_path
%li= active_link_to ‘Kittens’, kittens_path
%li= active_link_to ‘Froggies’, froggies_path
[/ccN_ruby]

And that’s the skinny of what active_link_to is for.

For more documentation on more functionality checkout project on GitHub: http://github.com/theworkinggroup/active_link_to

2 Responses to Active state for link_to == active_link_to. A solution for building navigation systems in Rails.

  1. Alpha says:
  2. Tobias says:

    Thanks for this post, that was exactly what I was looking for, much sweeter than those manual helper http://stackoverflow.com/questions/2120716/rails-select-current-menu-item

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>