Question

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?

Was it helpful?

Solution

This is not the best way to do it, but will give you some thoughts on pulling the current controller and action.

You can look at https://github.com/weppos/tabs_on_rails for more ideas on how to make it cleaner code. But this requires a bit more setup. You would create a tabs_tag function that would check the current page and do different styling. Personally, I didn't care for this gem too much and prefer to style my pages my own way.

<%= tabs_tag do |tab| %>
  <%= tab.home      'Homepage', root_path %>
  <%= tab.dashboard 'Dashboard', dashboard_path %>
  <%= tab.account   'Account', account_path %>
<% end %>

if "#{controller.controller_name.to_s}.#{controller.action_name.to_s}" == "pages.index"
  <li class='active'>
else
  <li>
end

or use a helper method

def current_page(page,action)
  if controller.controller_name.to_s == page && controller.action_name.to_s == action
    'active'
  else
    'not_active'
 end
end

and in your view

<li class="<%= current_page('pages','index') %>">

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top