Search code examples
javascriptvariablesfor-loopmustachedeclare

Mustache variable declaring


var page = {
    pageCount : 3,
    pageNum : [
        //loop script to create '"num" : "x"'
    ]
};
var pageTemplate = '{{#pageNum}} <div id="page{{num}}" class="pages"> page {{num}} </div> {{/pageNum}}';
var pageHtml = Mustache.to_html(pageTemplate, page);

Is it possible to create a for loop or some sort to create num variables in accordance to pageCount like this:

for (var x = 0; x <= pageCount; x++)

It produces a syntax error so I want to know if there are other alternatives to do this. Thanks


Solution

  • From the fine manual:

    Enumerable Sections

    [...] Use {{.}} to access the current item inside the enumeration section.

    So all you need to do is put the numbers in pageNum:

    var page = {
        pageCount : 3,
        pageNum : [ ]
    };
    for(var i = 0; i < page.pageCount; ++i)
        page.pageNum[i] = i + 1;
    

    And then use {{.}} to access them in the template:

    {{#pageNum}} <div id="page{{.}}" class="pages"> page {{.}} </div> {{/pageNum}}