Never been to DZone Snippets before?

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

Highlight link for current action (See related posts)

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;
}


You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts