2

I have simple navigation bar in my rails app(Home, News, Contact, etc). And I need to define current page to add :class => 'active'. I find few solution to define current page. And I even created own version. But all of them are reduced to one:

<li class=<%= current_page?(tratata) ? "active" : nil %>...</li>

How I can to apply this solution to all <li> - elements but not to write this every time?

Eugene
  • 689
  • 6
  • 20

2 Answers2

2

One way to do this is to check if the page the user is on matches the name of the controller they're visiting (you could also do a controller name / action name combination for extra specificity).

application_helper

def nav_helper(arg)
  controller_name == arg ? "current" : ""
end

view

<li class="<%= nav_helper('about') %>">
  <a href="#">A link</a>
</li>

EDIT:

Woops, I wrote this before you edited your question. To add this to all 'li' tags, use another helper which uses content_tag and place the nav_helper method inside of it.

John
  • 3,296
  • 2
  • 24
  • 36
  • I Understood and `content_tag` would be nice but my navbar is not generate dinamically. I need to use this helper for each `
  • ` elements?
  • – Eugene Jul 22 '12 at 07:05