DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Access Parent Data Array From Nested JQuery Templates
<script id='section-template' type='text/html'>
<section>
<header class='header'>
<h3 class='title'>${title}</h3>
</header>
{{tmpl(columns) "#column-template"}}
</section>
</script>
<script id='column-template' type='text/html'>
${index_class = _.indexClass(p, this.parent.data.c.length), ''}
<section class='${index_class} column'>
<header class='header'>
<h4 class='title'>${title}</h4>
</header>
<dl>
{{each(i, term) terms}}
${index_class = _.indexClass(terms.position, $data.terms.length), ''}
<dt class='${index_class}'>${term.key}</dt>
<dd class='${index_class}'>${term.value}</dd>
{{/each}}
</dl>
</section>
</script>
// underscore.js mixin to find list class, not relevant to finding the index in jquery.tmpl, but useful otherwise.
_.mixin({
indexClass: function(index, length) {
var result;
result = index % 2 === 0 ? "even" : "odd";
if (index === 0) {
result += " first";
} else if (index === length - 1) {
result += " last";
}
return result;
}
});
columns = []
columns.push({title: "First Column", position: 0, terms: [{key: "One", value: 1, position: 0}, {key: "Two", value: 2, position: 1}]});
columns.push({title: "Middle Column", position: 1, terms: [{key: "A", value: "a", position: 0}, {key: "B", value: "b", position: 1}]});
columns.push({title: "Last Column", position: 2, terms: [{key: "X", value: "x", position: 0}, {key: "Y", value: "y", position: 1}]});
$("#section-template").tmpl({title: "Managing Lists in jQuery.tmpl" columns:columns}).appendTo("body")





