ed1t
ed1t

Reputation: 8709

Navigation menu in rails

I have my navigation menu in application.html and the menu has class="active" . That depends on the page the user is on. How can I dynamically figure out which item needs to have the class:

Here's how my top menu bar is:

<ul>
   <li class="active"><a href="#">Home</a></li>
   <li><a href="#">Page1</a></li>
   <li><a href="#">Page2</a></li>
   <li><a href="#">Page3</a></li>
</ul>

Upvotes: 1

Views: 4046

Answers (3)

Uchenna
Uchenna

Reputation: 4089

you can create a siple helper like this

  def  nav_link(name, url)
    selected = url.all? { |key, value| params[key] == value }
    link_to(name, url, :class => (selected ? "youarehere tabs" : "tabs"))
  end

<div id="tabs" class="tabs2">
  <%= nav_link %>
  <%= nav_link %>
  <%= nav_linl  %>
</div>

then add the necessary css styles

Upvotes: 0

theIV
theIV

Reputation: 25794

The easiest (and possibly the most rudimentary) is to use current_page?. You can read up in the docs to see how it works. As I've experienced, it does not always produce what you want.

There is also a gem, navigasmic, which works pretty well if your needs get fairly complex.

There are a number of ways to accomplish what you are trying to do. Try out current_page? first and if you find yourself ripping your hair out, move on to something like navigasmic.

Upvotes: 1

brentvatne
brentvatne

Reputation: 8036

One way would be to have an @active_page instance variable in the controllers, which you set on each action. You may also do this already with a title (@title maybe?), so perhaps you could use that instead. Then in the template:

<li class="<%= "active" if @active_page == "Home" %>">...</li>

Upvotes: 2

Related Questions