Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mustache

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

like image 830
MustacheNewbe Avatar asked Jan 04 '11 10:01

MustacheNewbe


People also ask

What is mustache syntax?

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.

What are mustache files?

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.

What is mustache in html?

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


2 Answers

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

like image 150
mmaclaurin Avatar answered Sep 19 '22 17:09

mmaclaurin


Use {{@index}} inside iteration.

{{#data}}
    <p>Index is {{@index}}</p>
{{/data}}
like image 32
Dmitrii Malyshev Avatar answered Sep 17 '22 17:09

Dmitrii Malyshev