Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to add "current" class to nav in Rails 3

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......

like image 927
PeterWong Avatar asked Sep 14 '10 03:09

PeterWong


4 Answers

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>
like image 179
Skilldrick Avatar answered Nov 18 '22 06:11

Skilldrick


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).

like image 22
jpemberthy Avatar answered Nov 18 '22 05:11

jpemberthy


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…

like image 55
Yannis Avatar answered Nov 18 '22 04:11

Yannis


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) %>
like image 26
Peyton Avatar answered Nov 18 '22 06:11

Peyton