views:

865

answers:

6

Right now I have a navigation partial that looks like this (x10 buttons)...

<% if current_controller == "territories" %>
    <li><%= link_to "Territories", {:controller => 'territories'}, :class => 'active'  %></li>
<% else %>
    <li><%= link_to "Territories", {:controller => 'territories'}  %></li>
<% end %>
<% if current_controller == "contacts"  %>
    <li><%= link_to "Contacts", {:controller => 'Contacts'}, :class => 'active'  %></li>
<% else %>
    <li><%= link_to "Contacts", {:controller => 'Contacts'}  %></li>
<% end %>

Is there a more elegant/DRY solution for doing this?

+1  A: 

Check out link_to_unless_current. Not exactly what you asked for, but it's close.

Also, you could put this kind of logic in a helper to abstract it out of the view.

zenazn
+2  A: 

It's pretty easy to see where the repetition is in there. It's all of the general form:

<% if current_controller == XXXXX %>
  <li><%= link_to XXXXX, {:controller => XXXXX}, CLASS %></li>
<% else %>
  [do the same stuff minus ":class => 'active'"]
<% end %>

So we want XXXXX and CLASS to be variables (since those are the only things that change) and the rest can be a simple template.

So, we could do something like this:

%w(Contacts Territories).each |place|
  <% class_hash = current_controller == place ? {:class => 'active'} : {}
  <li><%= link_to place, {:controller => place}, class_hash)</li>
Chuck
+5  A: 

In a similar vein to what Chuck said:

<% TARGETS.each do |target| %>
  <li>
    <%= link_to target.humanize, 
      { :controller => target }, 
      class => ('active' if current_controller == target))
  </li>
<% end %>
kch
+1  A: 

A slightly different version w/ link_to_unless_current:

<ul>
<% links.each do |link| -%>
<li><%= link_to_unless_current link.humanize, { :controller => target } %></li>
<% end -%>
</ul>

A good resource for stuff like this are the rails docs. Railsbrain.com has a really good interface for the rails documentation.

vrish88
+1  A: 

Check out rails-widgets on github. It provides a ton of convenience helpers for rails UI stuff (tabnavs, tooltips, tableizers, show hide toggle, simple css progressbar) in addition to navigation.

Here are the docs

chaostheory
A: 

Check out the simple-navigation plugin. It's an 'easy to use' rails plugin for creating navigations for your rails apps.

Andi Schacke