Sometimes views can get unavoidably large (think eBay registration form). And sometimes it’s nice to group related content within a view. Well, in either case, here’s an option to do just that.
I found a prototype extension, Control.Tabs which basically gives you a menu to show certain pieces of markup. It suited my needs and here’s how I tied it into Rails.
I didn’t want to fiddle with javascript each time I needed this in a view, so I created a block helper to do the work for me1:
def tabbed_content(*links, &block) dom_id = links.last.is_a?(Hash) ? links.pop.values.last : 'tabbed-menu' list_items = links.inject([]) { |items, link| items << content_tag(:li, link_to(link.to_s.capitalize, "##{link.to_s.downcase}")) } tabs = content_tag(:ul, list_items, :id => dom_id) concat tabs, block.binding yield concat javascript_tag("new Control.Tabs('#{dom_id}');"), block.binding end
Now when a view gets inherently too large (or needs grouped), I can make it scroll-friendly and simplify the code. As an example, here’s how I’d use it to section off someone’s online resume.
<% tabbed_content :education, :work, :references do -%> <div id='education'> <h2>Education Background</h2> <p>whatever you want</p> </div> <div id='work'> <h2>Work Experience</h2> <p>whatever you want</p> </div> <div id='references'> <h2>References</h2> <p>whatever you want</p> </div> <% end -%>
This will place a set of links (capitalized versions of what was passed in) at the top of the content, defaulting to the first section. As expected, clicking a link will show only that section. And the javascript writes an “active” class to the appropriate link, which is nice for the CSS.
As a side note, there is a default DOM id being written to the <ul>, but it can be overridden if desired (maybe there’s more than one on a page?).
<% tabbed_content :education, :work, :references, :dom_id => 'tabbed-menu-2' do -%>
I know this is incredibly simple and basic, but someone might find it useful. And of course, if you do happen to use this, make sure you have the Control.Tabs javascript library included in your layout as needed (Chris has a tip for that).
1 Note: in Rails 2.0 extract_options! could be used instead of manually checking if the last item is a Hash, which is something I currently do a lot.





