htmlruby-on-railshtml-listscurrent-page

Current page class in rails app


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?


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') %>">