How to set a tab active when the nav bar is in the application template?

I have a simple nav bar like so:

<ul class="nav">
   <li><a href="<%= index_url %>">Home</a></li>
   <li><a href="#about">About</a></li>
   <li><a href="<%= users_url %>">Users</a></li>

Which is part of the application.html.erb file in a rails project. I would like the class="active" attribute to be set on whatever the current page is, however this is complicated since the nav bar is in the template that yields to the rest of the app with <%= yield %>. How can I reliably set the active tab based on what page I'm loading?

...javascript removed because it was distracting from the actual question.

To clarify:

Rails loads the application.html.erb which renders everything up to and including this nav before calling <%= yield %> and rendering whatever view I'm loading.

I want the "Users" tab to have the class="active" when I'm displaying the users/index.html.erb file, or the users/show.html.erb (basically anything from the user model) is there a proper rails way to do this?

I know I could move the nav bar to each model's view template and manually set the active class, but that's not very "DRY".


Probably not exactly what you're looking for, but I typically just write a quick helper named "tab" that lets me set a variable into my view for the tab, and then use conditionals to set up the class on the tabs.

# Helper
def tab(value)
  @page_tab = value

# View
<% tab "about" %>

# Layout    
<ul class="nav">
   <li><a href="<%= index_url %>" <%= class=\"active\" if @page_tab == "home" %>>Home</a></li>
   <li><a href="#about" <%= class=\"active\" if @page_tab == "about" %>>About</a></li>
   <li><a href="<%= users_url %>" <%= class=\"active\" if @page_tab == "users" %>>Users</a></li>

Need Your Help

Add Attachment to a custom form in Orchard

orchardcms orchardcms-1.8 orchard-modules

I want to add a field in Orchard custom form so user can use it to upload a file with certain document type and size.