elektrorl
elektrorl

Reputation: 620

Index of a numbered array of key:value in Mustache.js

I have this object:

{nodes: [
        {
            node: {
                actors: {
                    1: "Actor 1",
                    2: "Actor 2"
                }
            }
        }]

In my Mustache template, I tried this and it worked:

{{#actors}}
   {{1}}<br />
   {{2}}
{{/actors}}

But I dont know how much actors I have, I need something like an index. It seems that handlebars.js knows how to do this, but I want to use Mustache.js.

Upvotes: 0

Views: 879

Answers (1)

TheDude
TheDude

Reputation: 3952

I would change the format of the JSON so it is like:

"actors": [ {"name": "Actor 1"}, {"name": "Actor 2"}]

Then you can do

{{#actors}}
  {{name}}
{{/actors}}

If you wanted to use Handlebars, you can specify a helper for this:

Handlebars.registerHelper('eachProperty', function (context, options) {
    var ret = "";
    for (var prop in context) {
        if (prop)
            ret = ret + options.fn(({ property: prop, value: JSON.stringify(context[prop]) }));
    }
    return ret;
});

So when you wanted to iterate over an object's properties, you can do:

{{#eachProperty actors}}
  {{value}}
{{/eachProperty}}

Also note that {{property}} would give you the index value for the object.

Upvotes: 1

Related Questions