I have some static pages in a navigation menu. I want to add a class like "current" to the item which is currently displaying.
The way I am doing so is to add tons of helper methods (each for one item) to check the controller and action.
def current_root_class
'class="current"' if controller_name == "homepage" && action_name == "index"
end
<ul>
<li <%= current_root_class %>><%= link_to "Home", root_path %>
Is there any better way to do so!? My current way is so stupid......
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>
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)
.
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…
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) %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With