Skip to content

Instantly share code, notes, and snippets.

@greypants
Forked from reagent/nav_link.rb
Last active October 17, 2023 05:49
Show Gist options
  • Save greypants/3279194 to your computer and use it in GitHub Desktop.
Save greypants/3279194 to your computer and use it in GitHub Desktop.
RAILS 3: nav_link helper for adding 'selected' class to navigation elements

UPDATE: It's a gem!

This helper has finally been moved into a gem called nav_lynx!

https://github.com/vigetlabs/nav_lynx

http://rubygems.org/gems/nav_lynx

Thanks to @brianjlandau and @reagent for getting that set up and tested!

Behold, the nav_link:

The nav_link helper works just like the standard Rails link_to helper, but adds a 'selected' class to your link (or its wrapper) if certain criteria are met. By default, if the link's destination url is the same url as the url of the current page, a default class of 'selected' is added to the link.

<%= nav_link 'My Page', my_path %>

When my_path is the same as the current page url, this outputs:

<a class="selected" href="http://example.com/page">My Page</a>

For more options and full usage details, see: http://viget.com/extend/rails-selected-nav-link-helper

Drop nav_link_helper.rb into app/helpers in your Rails 3.x app and enjoy.

UPDATE: Now with block support!

Same usage as link_to:

<%= nav_link 'http://example.com/page' do %>
  <strong>My Page</strong>
<% end %>
@C-E-Rios
Copy link

How can I make this work to ensure the when a user lands on the home-page the home tab is 'selected'?

Currently no tabs are selected when you land on the website.

Thanks.

@greypants
Copy link
Author

@diegocouto
Copy link

It seems to be running smoothly also on Rails 4, so maybe the Gem dependency could be updated.

And by the way, thanks for this! :-)

@greendezine
Copy link

Just what I needed, and working great on Rails 4! In a similar fashion to how url_segment works, Is it possible to add the selected class to all pages under a sub-directory structure ?

For example: admin/products/item, admin/products/list etc.. Automatically adding the "selected" class to all urls within "/products" (within the same controller)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment