Recursive List Building With Handlebars
Recursively building lists with Handlebars using partials.
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.1/handlebars.min.js"></script>
<script id="list" type="x-handlebars-template">
{{#each items}} {{! Each item is an "li" }}
<li>
{{name}} {{bill}}
{{#if items}} {{! Within the context of the current item }}
<ul>
{{> list}} {{! Recursively render the partial }}
</ul>
{{/if}}
</li>
{{/each}}
</script>
<script id="main" type="x-handlebars-template">
<ul>
{{> list}}
</ul>
</script>
JavaScript
// Tree data.
var items = [
{ name: "foo1",bill: "YEs" },
{ name: "foo2" ,bill: "YEs" },
{ name: "foo3", bill: "YEs" , items: [
{ name: "foo4" ,bill: "YEs" },
{ name: "foo5" ,bill: "YEs" },
{ name: "foo6",bill: "YEs" , items: [
{ name: "foo7" ,bill: "YEs" }
]}
]},
{ name: "foo8",bill: "YEs" }
];
// The main template.
var main = Handlebars.compile( $( "#main" ).html() );
// Register the list partial that "main" uses.
Handlebars.registerPartial( "list", $( "#list" ).html() );
// Render the list.
$( "body" ).html( main( { items: items } ) );