14 Mar 2007 johnnyb   » (Journeyer)

Simple Tabbed Pane/Panel using Rails

app/helpers/application.rb:


def tabbed_panel(base_id, &block)
	panels = []


concat("<div class='tabbed_panel' id='" + base_id + "'>\n", block.binding); concat("<ul class='tabselector' id='" + base_id + "_tabs'>\n", block.binding);

yield panels panels.each do |panel| concat("<li class='pane_tab tab_unselected' id='" + panel[2] + "_tab'>" + link_to_function(panel[0], "select_panel('" + base_id + "', '" + panel[2] + "')") + "</li>", block.binding) end

concat("</ul>\n", block.binding); concat("<ul class='tabpanes' id='" + base_id + "_panels'>\n", block.binding); panels.each do |panel| concat("<li class='panel_panel panel_unselected' id='" + panel[2] + "_panel'>" + panel[1] + "</li>\n", block.binding) end concat("</ul>\n", block.binding); concat("</div>\n", block.binding); end

public/javascripts/panel.js:


function select_panel(baseid, panel_id_base) {
	var tabs = $(baseid + "_tabs").childNodes;
	var tab_id = panel_id_base + "_tab";
	var panel_id = panel_id_base + "_panel";
	$A(tabs).each( 
		function(the_tab) {
			if(the_tab.nodeName == "LI") {
				the_tab.removeClassName("tab_unselected");
				the_tab.removeClassName("tab_selected");
				if(the_tab.id == tab_id) {
					the_tab.addClassName("tab_selected");
				} else {
					the_tab.addClassName("tab_unselected");
				}
			}
		}
	);
	var panels = $(baseid + "_panels").childNodes;
	$A(panels).each(
		function(the_panel) {
			if(the_panel.nodeName == "LI") {
				the_panel.removeClassName("panel_unselected");
				the_panel.removeClassName("panel_selected");
				if(the_panel.id == panel_id) {
					the_panel.addClassName("panel_selected");
				} else {
					the_panel.addClassName("panel_unselected");
				}
			}
		}
	);
}

public/stylesheets/panel.css:


/* Clearly you need better CSS, but this is a decent start */
.panel_selected { display: block; }
.panel_unselected { display: none; }
.tab_selected { background-color: gray; }
.tab_unselected { background-color: white; }

Then, to use it in your rails app, just put this in the view:


<% 
#3-panels to choose from in the following example:
tabbed_panel 'all_props' do |panels| 
	panels << ["Form Properties", render(:partial =>
"basic_info"), "fprops"]
	panels << ["Toolbox", render(:partial =>
"toolbox"), "tbox"]
	panels << ["Element Properties", render(:partial =>
"properties"), "eprops"]
end 
%>

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!