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..??
Mustache is a logic-less template syntax. It can be used for HTML, config files, source code - anything. It works by expanding tags in a template using values provided in a hash or object. We call it "logic-less" because there are no if statements, else clauses, or for loops.
Mustache is a logic-less templating system. It permits you to use pre-written text files with placeholders that will be replaced at run-time with values particular to a given request. For more general information on Mustache, consult the mustache specification.
Mustache is described as a logic-less system because it lacks any explicit control flow statements, like if and else conditionals or for loops; however, both looping and conditional evaluation can be achieved using section tags processing lists and anonymous functions (lambdas).
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
Use {{@index}} inside iteration.
{{#data}}
<p>Index is {{@index}}</p>
{{/data}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With