30

in the bootstrap navigation bar. You can get the effect of a button being clicked by adding the class active . Naturally, I want to use this on my pages. For example if I'm on the about us page I want the about us button clicked.

What is the best way to go about this? I was going to go to each page and at the bottom have a jQuery function add the class active to it. Is there a better way?

rails_id
  • 8,120
  • 4
  • 46
  • 84
Alain Goldman
  • 2,896
  • 5
  • 43
  • 75

7 Answers7

58

Read about current_page? here

You can add a method for handle logic with current_page?, example a method :

module ApplicationHelper

 def active_class(link_path)
  current_page?(link_path) ? "active" : ""
 end

end

example bootstrap navbar template

<div class="navbar">
  <div class="navbar-inner">
    <a class="brand" href="#">Title</a>
    <ul class="nav">
      <li class="active"><a href="#">Home</a></li>
      <li><a href="#">Link</a></li>
      <li><a href="#">Link</a></li>
    </ul>
  </div>
</div>

So, on view looks like

HTML

<li class="<%= active_class(some_path) %>">
<%= link_to "text of link", some_path %>
</li>

HAML

%li{:class => active_class(some_path)}
  = link_to "text of link", some_path

Or you can use request.fullpath to get current full of path if a current path have a parameter

example

<ul>
 <% Contry.all.each do |c| %>
  <li class="snavitem <%= active_class(contry_path(c)) %>">
    <%= link_to "show #{c.name}", contry_path(c) %>
  </li>
 <% end %>
</ul>

and on your application_helper.rb

def active_class(link_path)
  request.fullpath == link_path ? "active" : "" 
end

read about request.fullpath here

rails_id
  • 8,120
  • 4
  • 46
  • 84
14

in my opinion, a cleaner way to achieve that is to write a link_to_in_li method in application_helper.rb:

def link_to_in_li(body, url, html_options = {})
  active = "active" if current_page?(url)
  content_tag :li, class: active do
    link_to body, url, html_options
  end
end

then use it this way

<%= link_to_in_li "Home", root_path, id: "home_link" %>

I find the code inside li a little difficult to read.

Wawa Loo
  • 2,266
  • 18
  • 15
  • 2
    Very clever in Rails way. – R Milushev Dec 19 '14 at 13:49
  • 1
    Easiest answer I found. Also, if you need to have multiple classes on the
  • element you can simply add the additional classes like so: ``content_tag :li, class: "#{active} other-class" do``
  • – samuelkobe Jan 21 '15 at 01:56
  • 1
    This works great, I've been trying many other solutions and this is the best for me. – scottknight Feb 06 '15 at 22:24
  • I think this is the best solution I've read up to now. It is DRY, and it only requires to add `_in_li` to the url helpers you might already have, because it takes the same arguments. Thanks. – user2553863 Oct 30 '17 at 15:36