← Back to home

link_to_tagged_current

April 09, 2008

Almost every site has some sort of tabbed navigation. There are a lot of alternatives of how to accomplish it. One way that comes to my mind is Paolo Dona’s widgets plugin. But sometimes I want something lighter, and link_to_unless_current is way too simple. So I created link_to_tagged_current, a very simple rails helper that in difference of link_to_unless_current, when current, it creates the link + it adds the class current to it.

In app/helpers/application_helper.rb

def link_to_tagged_current(name, options = {}, html_options = {}, &block)
  if current_page?(options)
    html_options[:class] = "#{html_options[:class].to_s} current".strip
  end
  link_to name, options, html_options, &block
end

After little use, this was still pretty simple, so I added a :highlights_on option.

def link_to_tagged_current(name, options = {}, html_options = {}, &block)
  current = false
  highlights = html_options[:highlights_on] ? html_options[:highlights_on] + [options] : [options]

  highlights.each do |h|
    if (h[:controller] == @controller.controller_name and !h[:action]) or
       (h[:controller] == @controller.controller_name and h[:action] == @controller.action_name and !h[:id]) or
       (!h.kind_of?(Hash) and current_page?(h))
      current = true
      break
    end
  end

  if current
    html_options[:class] = "#{html_options[:class].to_s} current".strip
  end

  html_options[:highlights_on] = nil
  link_to name, options, html_options, &block
end

Some usage examples are:

link_to_tagged_current 'Dashboard', dashboard_url
link_to_tagged_current 'Users', users_url, :highlights_on => [:controller => 'admin']

Given this is a very common need I will try to push it to rails.

UPDATE: Rails core member Pratik said that it should stay as a plugin for now. You can see the ticket here.

← Back to home