blog.robotex.de

Rails3: How to hightlight the current link

Highlighting the current link is a pattern, that you'll need on almost all pages.

I googled the problem and got to this page. Some guy posted a comment with a link to here. I liked the approach from the moment i saw it. Unfortunately it didn't work "out-of-the-clipboard" (seems to be for rails 2.x), so I had tweak it.

Here is what I came up with:

Rails.root/app/helpers/application_helpers.rb:

module ApplicationHelper
  class CurrentPageDecorator
    def initialize(helper,options)
      @helper = helper
      @html_class = options[:class] || 'active'
    end
    
    def link_to(*args,&blk)
      name = args.first
      options = args.second || { }
      html_options = args.third || { }
      if @helper.current_page?(options)
        html_options[:class] = (html_options.has_key?(:class)) ? "#{html_options[:class]} #{@html_class}" : @html_class
      end   
      @helper.link_to(name,options,html_options,blk)
    end
  end

   
  def highlight_current_link(options = { },&blk)
    raise ArgumentError unless block_given?
    yield CurrentPageDecorator.new(self,options)
    nil
  end  
end

In your views:

<ul>
<%= highlight_current_link do |n| %>
  <li class="span-6" id="clinic">
    <%= n.link_to 'Klinik', template_path("praxis/clinic"), :id => 'clinic_link' %>
  </li>

  <li class="span-6" id="office_tour">
    <%= n.link_to 'Office Tour', template_path("praxis/office_tour"), :id => 'office_tour_link' %>
  </li>
<% end %>  
</ul>

To pass a custom html class for the active link you can do:

<%= highlight_current_link(:class => 'on') do |n| %>
.
.
.
<% end %>

Back