I have a menu which is a ul
Home | Calendar | Settings
I want to highlight (via a css class) the selected tab in the menu.
Some lin
Update to @ahmy's answer for Rails 3.2:
def menu_list_item(*args, &block)
url = args[1]
mapping = Rails.application.routes.recognize_path(url)
li_class = 'active' if mapping[:controller] == controller.controller_path
content_tag :li, :class => li_class do
link_to *args, &block
end
end
i.e. Rails.application.routes.recognize_path
instead of ActionController::Routing::Routes.recognize_path
.
I settled on this solution which I like a lot:
In the helper
def active_if(options)
if params.merge(options) == params
'nav-active'
end
end
And in the view define what makes the route unique:
<%= link_to 'Home', root_path, class: active_if(action: 'home') %>
<%= link_to 'Aricles', articles_path, class: active_if(controller: 'articles') %>
In your helper file:
def is_active?(page_name)
"active" if params[:action] == page_name
end
In the template file:
link_to 'Home', '/', :class => is_active?("index")
link_to 'About', '/about', :class => is_active?("about")
link_to 'contact', '/contact', :class => is_active?("contact")
I found this on: http://juliocapote.com/post/52081481/highlight-link-based-on-current-page-in-rails
I have the same problem and end up creating helper. basicly it replace the link_to url helper so it wrap the link with li and add class "menu_selected" if the current controller matches the link controller
usage sample
<%= menu_link_to "Home", home_path %>
def menu_link_to(*args, &block)
url = args[1]
mapping = ActionController::Routing::Routes.recognize_path(url)
class_property = "menu_selected" if mapping[:controller] == controller.controller_path
content_tag :li, :class => class_property do
link_to *args, &block
end
end
The simplest way would be to check which controller is being used. I made up controller names, so of course you would replace 'home', 'calendar', and 'settings' with the correct names.
<ul>
<li class="<%= "highlighted" if params[:controller] == "home" %>">Home</li>
<li class="<%= "highlighted" if params[:controller] == "calendar" %>">Calendar</li>
<li class="<%= "highlighted" if params[:controller] == "settings" %>">Settings</li>
</ul>