DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Jonathan has posted 1 posts at DZone. View Full User Profile

Highlight Link For Current Action

05.14.2006
| 16717 views |
  • submit to reddit
        It's very common to want to highlight the current link within a navigation list for the current action being performed.

What follows is an extremely simplistic approach to solving this, so build upon it as you wish.


The first thing to do is add the following code to your application_helper.rb file
def section_link(name,options)
    if options[:action] == @current_action and options[:controller] == @current_controller
       link_to(name, options, :class => 'on')
    else
      link_to(name,options)
    end
end

The above method always expects an :action key to be passed in with the options hash, so if you're one of those people who just pass in the :controller and not the :action so as to default to whatever method you've set it in your routes.rb file, then this won't work for you.

Finally put this in you're application.rb file, as it makes the current executing action and controller name available to the helper.
before_filter :instantiate_controller_and_action_names

def instantiate_controller_and_action_names
      @current_action = action_name
      @current_controller = controller_name
end 


In your view use 
<%=section_link('Home',:controller => 'articles', :action => 'index')%>

Make sure you have a CSS class called "on" or edit the above code. The following CSS is just an example.

a.on{
  border-bottom: solid 2px #000;
}
 
    

Comments

Prasanna Laguduva replied on Tue, 2009/05/12 - 2:41pm

in above example, is "action_name" a keyword? I have two related actions (update and delete). I would like to use the same controller and also reuse some of the methods in the controller.