Is there a way to set a counter in a mustache iteration?

MustacheNewbe picture MustacheNewbe · Jan 4, 2011 · Viewed 14k times · Source

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..??

Answer

mmaclaurin picture mmaclaurin · Jul 8, 2011

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