17
Jun
09

Super Easy Tabs in Rails

All the cool kids these days seem to be doing navigation via tabs, and since I want to be cool, too, I figured I might as well do it to. Ya, sure, there are plenty of plugins out there that do this, but it always seems like these things have too much configuration and code for its own good.

So, I went at it on my own and, really, if the tabs are simple, the solution is pretty simple. My tabs are based on the controller name, which means the current tab maps to all the actions of a certain controller. In other words, it’s kind of the way Basecamp does it.

First, let’s start with some code in the controller. In my app, everything that uses tabs is inherited from a base controller called LoginProtectedController. That’s where I put this code, but it would work just as well in the ApplicationController:

  helper_method :current_tab

  def self.current_tab(tab_name)
    before_filter do |controller|
      controller.send(:current_tab=,tab_name)
    end
  end

  protected

  def current_tab=(tab_name)
    @current_tab = tab_name
  end

  def current_tab
    @current_tab || controller_name.titleize
  end

So, this is what I have in one of my controllers to mark that the tab is not the name of the controller, but called ‘Dashboard’

  current_tab 'Dashboard'

Now for some helper code for displaying the tabs:

  def tab_link(args={})
    html_options = {}
    html_options = {:class=>'current'} if args[:tab] == current_tab
    link_to args[:tab], args[:path], html_options
  end

And here’s how you put it together in the view:

<div id="navigation">
  <%= tab_link("Dashboard", :path=>admin_path) %>
  <%= tab_link("Items", :path=>admin_items_path) %>
  <%= tab_link("Users", :path=>admin_users_path) %>
  <%= tab_link("Account", :path=>edit_admin_account_path) %>
</div>

If you want to make it look all pretty, some CSS should spruce it up:

#navigation {
  line-height: 100%;
  margin-left: 6px;
  float: left;
  font-size: 12px;
}

#navigation a {
  background-color: #CCCCCC;
  color: #000000;
  padding: 7px 15px;
  text-decoration: none;
  display: block;
  float: left;
  margin-left: 2px;
}

#navigation a:hover {
  background-color: #BBBBBB;
}

#navigation a.current, #navigation a.current:hover {
  background-color: #FFFFFF;
}

Advertisement

0 Responses to “Super Easy Tabs in Rails”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Stay Updated

or

Get new posts via email

Software Blogs - BlogCatalog Blog Directory

 

June 2009
M T W T F S S
« May   Jul »
1234567
891011121314
15161718192021
22232425262728
2930  

Follow

Get every new post delivered to your Inbox.