I have a code that renders a mustache template with some iterations like:
{{#items}}
some html code....
{{/items}}
but I want to place into the iteration the number of item that is rendered, like that:
{{#items}}
This is the item [COUNTER-VAR]
{{/items}}
There is some way to perform this..??
Handlebars no longer necessary. You can use the high order sections in current mustache. These basically let you call a function with the contents of the section as an argument. If that section is inside an iteration it will be called for each item in an iteration.
Given this template (kept in a script tag for convenience & clarity)
<script type="text/html" id="itemview">
<table width="100%" border="0" cellspacing="0" cellpadding="3">
<tbody>
{{#items}}
<tr>
<td>{{#count}}unused{{/count}}</td>
<td>{{.}}</td
</tr>
{{/items}}
</tbody>
</table>
</script>
...and the following code, you can build a numbered list.
function buildPage(root)
{
var counter = 0;
var data = {
'items': [ 'England', 'Germany', 'France' ],
'count' : function () {
return function (text, render) {
// note that counter is in the enclosing scope
return counter++;
}
}
};
// fetch the template from the above script tag
var template = document.getElementById('itemview').innerHTML;
document.getElementById("results").innerHTML = Mustache.to_html(template, data);
}
Output: 0 England 1 Germany 2 France