Home
Run

Tree view: using recursive nested {{tmpl}} tags.

Data:

var rootFolder = {
	name: "Categories",
	folders: [
		{ name: "Drama", folders: [
			{ name: "Courtroom" },
			{ name: "Political" }
		]},
		{ name: "Classic", folders: [
			{ name: "Musicals", folders: [
				{ name: "Jazz"},
				{ name: "R&B/Soul"}
			]},
		]}
	]
};

/* Array for the folder items. Each item can show up in one or more folders */
var movies = [
	{ name: "12 Angry Men",
		folders: [ "Courtroom" ],
		description: "A jury of 12 men must decide the fate of an 18-year-old boy."
	},
	{ name: "Word of Honor",
		folders: [ "Courtroom", "Classic" ],
		description: "One man's word against the U.S. military."
	}
];

HTML:

<script id="folderTemplate" type="text/x-jquery-tmpl">
	<li>
		{{if hasContent($data)}}
			<span class="toggle">${$data.expanded ? "-" : "+"}</span>
		{{/if}}
		<span>${name}</span>
	</li>
	{{if expanded}}
		<li>
			<ul>{{tmpl(getFolderItems(name)) "#itemTemplate"}}</ul>
			<ul>{{tmpl($data.folders || []) "#folderTemplate"}}</ul>
		</li>
	{{/if}}
</script>

<script id="itemTemplate" type="text/x-jquery-tmpl">
	<li class="folderItem">${name}</li>
</script>

Script:

$( "#folderTmpl" ).tmpl( folders ).appendTo( "#movieList" );

$( "#movieList" )
	.delegate( ".toggle", "click", function() {
		/* Toggle expanded property on data, then update rendering */
		var tmplItem = $.tmplItem( this );
		tmplItem.data.expanded = !tmplItem.data.expanded;
		tmplItem.update();
	})
	.delegate( ".folderItem", "click", function() {
		alert( $.tmplItem( this ).data.description );
	});