Call us at (416) 850-2500 - Visit us at 639 Queen St. W, Suite 502, Toronto, Ontario M5V 2B7
  Posted by Oleg on November 27th, 2009

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:

%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

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:

sudo gem install active_link_to

And then change our nav a bit:

%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

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:

%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

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

%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

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

Leave a Reply