Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Iterate over a hash in mustache.js

How to Iterate over a hash in mustache.js

Problem

Given this hash

a = {
  foo : { ... },
  bar : { ... },
  zap : { ... }
}

i want to Iterate over it but since the keys are different I am not sure how to in Mustache.js

the output will look something like this foo : (contents here)

Problem courtesy of: samccone

Solution

If you know the key in the nested Object that you're trying to retrieve, you can use a function.

see: http://jsfiddle.net/jimschubert/zPWDJ/

js:

$(function() {
    var names = {
        "a": [
            {"foo": { "name": "foo name"}},
            {"bar": { "name": "bar name"}},
            {"zap": { "name": "zap name"}}
        ],
        "n": function() {
            var self = this;
            var n = "";
            Object.keys(self).forEach(function(k, v) {
                if (typeof self[k] == "object") {
                    if(!n) n = self[k]["name"];
                }
            });
            return n;
        }
    };

    var template = $('#template').html();
    var out = $('#output');
    var html = Mustache.to_html(template, names);
    console.log(html);
    out.html(html);
});​

html:

Output

This of course assumes your data is an array of objects (the a in your post would be one key of a greater array, maybe?) If you don't have an array, I don't see why you wouldn't be able to adjust this for an object and make a getter function for whatever properties of each key you're looking for.

Solution courtesy of: Jim Schubert

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to Iterate over a hash in mustache.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×