I’ve got a JSON array of data and a jquery template.
I’ve got each of my “controls” templated and split out into their own files which I’m pulling in using jquery’s $.get(). The following simplified code/markup demonstrates:
<html>
<head>
<script type="text/javascript">
var payeeData = [
{
Name: "Ben Alabaster",
Address: "My Address"
},
{
Name: "Joe Bloggs",
Address: "Joe's Address"
},
{
Name: "John Doe",
Address: "Chez John"
}
];
$(function() {
$.get("./Templates/Payees.tmpl", function (template) {
$("#payeePlaceholder").replaceWith($.tmpl(template, payeeData));
});
});
</script>
<head>
<body>
<div id="payeePlaceholder" />
</body>
</html>
And the content of the template file in question:
<div class="togglePanel">
<table id="payeeData">
<tr>
<th>Payee</th>
<th>Address</th>
</tr>
<!-- Iterate here -->
{{each(idx,val)}}
<tr>
<td>${${val.Name}}</td>
<td>${${val.Address}}</td>
</tr>
{{/each}}
<!-- End iteration -->
<tr>
<td Colspan="2">${ArrayCount} Payees</td>
</tr>
</table>
</div>
In my actual production code, I have reason to not want to split out the iterated row into its own template, though I’ve considered nesting the template into an outer and inner if someone could demonstrate how but I haven’t been able to glean this from the documentation.
Right now if I push an array into the template engine, I end up with an iteration of this whole template for each item in the array, can anyone demonstrate how to get around that?
Might not be the most elegant solution, but it’s certainly the easiest one: wrap your array in an object, so the whole template would only render once and you can do your own iteration.
Then your templace would look like this: