Archive for the 'site navigation' Category

Highlight selected navigation item in ruby on rails

For an example site where I used this technique please refer to you’ll notice that when you click on best / worst or most recent it is highlighted with a black underline. This type of highlighting seems trivial. However to do it in rails in a nice elegant way is not obvious. So without further a do, I present my method. This method dis-involves the controller which makes for a cleaner more centralized place for managing your highlighted navigation.

The primary thing required is a method for creating navigation items. I choose to put my method / helper. in the app/helpers/application_helper.rb that way it will be available to all all of my views. The method I chose to use is

def nav_selected_no_span(hash_name, selectedkey )
                result =""
                hash_name.each do |item|
                        if(item[0].to_s== selectedkey)
                                result +="<li class="selected"+item[0].to_s.gsub(" ", "_").downcase+" selected">"+link_to(item[0].to_s,item[1].to_s)+"</li>"
                                result +="<li class=""+item[0].to_s.gsub(" ","_").downcase+" ns">"+link_to(item[0].to_s,item[1].to_s)+"</li>"
                  return result

This function is fairly, simple what it allows you to do in your view is, make an unorded list of your navigation items. You would use this method most likely in your app/views/layout/application.rb. An example of the navigation from is:

     <%= nav_selected_no_span([["Vote On Pets",home_path],["Best / Worst",best_worst_path],["Most Recent",most_recent_path]], params[:location] ) %>

The important thing to notice is the params[:location] the function above says that if params[:location] matches one of the names like “Vote On Pets” then highlight that item. Pretty simple. Then in your css you can define the rules that make something selected. Now you may be wondering where params[:location] is set. And you would be correct to wonder that. That parameter is actually set in your routes file believe it or not. As an example i’ll show you the route for “Vote On Pets”. located in config/routes.rb your could do something like this.

map.home '', :controller => 'index', :action => 'index', :location=>'Vote On Pets'

if you wanted most recent you would do something like this

map.most_recent '/most_recent', :controller=>'index',:action=>'recent',:location=>'Most Recent'

The location parameter is sent to the helper and the correct items is selected. So I hope this helps you in your efforts to stay dry and much more organized.

Questions and comments are very welcome on this blog. We like to know we are not talking to ourselves, so if you would like further explanation please feel free to post a comment.