Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Elegant way to handle navigation?

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?

like image 953
kush Avatar asked Mar 01 '09 23:03

kush


3 Answers

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 %>
like image 143
kch Avatar answered Oct 15 '22 09:10

kch


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>
like image 3
Chuck Avatar answered Oct 15 '22 10:10

Chuck


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

like image 2
chaostheory Avatar answered Oct 15 '22 09:10

chaostheory