ale
ale

Reputation: 11830

Slightly different content many Rails views - how to be DRY

Hopefully I haven't duplicated a question. It's similar to this one and this one but not quite.

On the subject of duplication, this is my problem. I'm new to Rails btw.

I have a (Twitter Bootstrap) set of pills/tabs and I want the <li> class to be set to "active" if the user is on the page associated with that tab. So far I'm doing it a stupid way.. in each of my views I have this (simplified):

<% content_for :pills do %>
  <li><a href="/">Home</a></li>
  <li class="active"><a href="/about">About</a></li> <----------- active class
  <li><a href="/contact">Contact</a></li>
<% end %>

and in each view I have the same code (doh) but with the class set to "active" on another tab/pill.

Most tab content comes from the same app/views/<some view directory>/ but one tab comes from app/views/<some OTHER view directory>/ but I guess this isn't a problem.

How do I solve this without repeating similar code in each view?

Many thanks.

Upvotes: 0

Views: 57

Answers (1)

aNoble
aNoble

Reputation: 7072

I've actually run into the same thing and created a helper that I've used in a few projects.

Add this to an app/helpers/layout_helper.rb file.

module LayoutHelper
  def nav_class_for(*controllers)
    :active if controllers.any? do |controller|
      controller_name.to_sym == controller.to_sym || params["#{controller.to_s.singularize}_id"]
    end
  end
end

Then I use it like this.

<li class="<%= nav_class_for(:about) %>"><a href="/about">About</a></li>

Just pass it the name of the controller or controllers that you want the menu item to be active for. It should also be active for any nested routes beneath those controllers.

Upvotes: 1

Related Questions