Best way to add "current" class to nav in Rails 3
Solution 1:
I made a helper called nav_link
:
def nav_link(link_text, link_path)
class_name = current_page?(link_path) ? 'current' : ''
content_tag(:li, :class => class_name) do
link_to link_text, link_path
end
end
used like:
nav_link 'Home', root_path
which will produce HTML like
<li class="current"><a href="/">Home</a></li>
Solution 2:
Use the current_page?
helper to determine whether or not you should assign the "current"
class. For example:
<%= 'active' if current_page?(home_about_path) %>
Note you can also pass a path (not only a hash of options), e.g: current_page?(root_path)
.
Solution 3:
Not truly an answer here, because I'm using quite the same way as you are. I've just defined helper methods to test for multiple controller or actions:
In application_helper.rb
def controller?(*controller)
controller.include?(params[:controller])
end
def action?(*action)
action.include?(params[:action])
end
Then you can use if controller?("homepage") && action?("index", "show")
in your views or other helper methods…
Solution 4:
I use this nav_link(text, link) function in application_helper.rb (Rails 3) to get the job done and it rolls my bootstrap twitter 2.0 nav bar links for me.
def nav_link(text, link)
recognized = Rails.application.routes.recognize_path(link)
if recognized[:controller] == params[:controller] && recognized[:action] == params[:action]
content_tag(:li, :class => "active") do
link_to( text, link)
end
else
content_tag(:li) do
link_to( text, link)
end
end
end
Example:
<%=nav_link("About Us", about_path) %>