Alex Rivera | Logout

Rails: Elegant way to handle navigation?

Asked 2009-03-01T23:49:27.423
12

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?

Edit
Report

1 Answer

3

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>
answered 2009-03-02T01:15:34.410

Your Answer