Add highlight link to current page in Rails

September 28, 2010 | In: Programming

I recently wanted to add a highlight link to a navigational element if the navigation was on the current page. I thought this would be pretty straight forward with Rails’ link_to helper. Turns out it was a little less-than-intuitive. So, to remind myself (and show others) how to do this, I’m providing the following:

<ul>
    <li>
        <%= link_to_unless_current "Home", root_path do
link_to "Home", root_path, :class => "current"
        end %>
    </li>
</ul>

In my research, I saw different ways of going about this, but this apparently is the recommended method as it’s in the documentation (see the URLHelper).

I have to say this seems a bit counter-intuitive and not as “easy” as it should be. I kept expecting to be able to do something like:

<%= link_to "Home" {home_path}, current_page? ? (:class => 'current') : nil %>

Anyway, if you want to add a highlight class, this works.



2 Responses to Add highlight link to current page in Rails

Eduardo

August 7th, 2012 at 11:40 am

Nice post :)

am

August 12th, 2012 at 4:45 am

module PagesHelper
def is_active?(page_name)
“selected” if params[:action] == page_name
end
end

Comment Form