rails
(5,110 views)

A tab helper that works for me

I loved the recent Tab Helper discussion on TheRailsWay.com, and this is what I ended up doing for my project.

I'm referring to this original post ( http://www.therailsway.com/2007/6/4/free-for-all-tab-helper ), all the comments therein, and the followup summary article ( http://www.therailsway.com/2007/6/28/free-for-all-tab-helper-summary )

While the pure css solution is elegant, it doesnt work so well for me because I need my tabs to be dynamic and decoupled from the controller.

Thus, Koz's Take is where I headed, although his answer is pretty sparse.

This is what I ended up with.

The following helper goes into application_helper.rb:

 # helper
  def tab_for(tab, link, label=nil)
content_tag :li, link_to(label||tab.to_s.titleize, link), :class => ("current_tab" if @current_tab == tab)
end

The helper is called in your view templates to render the tabs, perhaps as a _tabs partial called from a layout, as follows

# _tabs partial
<div id="tabs">
<ul>
<%# tab_for TAB_SYM, LINK [, TEXT] %>
<%= tab_for :projects, projects_path %>
<%= tab_for :user, user_path(current_user), "Contact" %>
</ul>
</div>

The instance variable @current_tab is set by any action to make one of the tabs current. This could be done in a before_filter,

# users_controller
before_filter :set_current_tab, :only => :show
  def set_current_tab
@current_tab = :user
end

Finally, css is used to make the <ul> and <li> tags into tabs:

# css based on http://www.alistapart.com/articles/slidingdoors2/
#tabs {
margin-top: 10px;
float:left;
width:100%;
background:#fff url("/images/tabs/tab2_bg.png") repeat-x bottom;
}
#tabs ul {
margin:0;
padding:10px 10px 0 10px;
list-style:none;
}
#tabs li {
float:left;
background:url("/images/tabs/tab2_left.png") no-repeat left top;
margin:0;
padding:0 0 0 9px;
}
#tabs a {
display:block;
background:url("/images/tabs/tab2_right.png") no-repeat right top;
padding:5px 35px 2px 6px;
text-decoration:none;
}
#tabs a:hover {
text-decoration: underline;
}
#tabs li.current_tab {
background-image:url("/images/tabs/tab2_left_on.png");
}
#tabs li.current_tab a {
background-image: url("/images/tabs/tab2_right_on.png");
padding-bottom:3px;
color:#fff;
}

 

Comments

by John Philip Green on Aug 22, 2007

>>

Nice and simple. I usually do something very similar.

by Thinkcast on Apr 04, 2008

>>

Nice solution, simple clean and elegant.

by Jay on Apr 29, 2009

>>

Hi, is there any way you could post the images?

by fashion guides on Sep 08, 2011

>>

I feel that it may be an interesting point, it made me think a bit. Thanks for sparking my thinking cap. Occasionally I get so much in a rut that I simply really feel like a record. <a href="http://fashiongirls.onsugar.com/">fashion guides</a>fashion guides

New Comment

markdown formatting permitted