Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Iterate over a hash in mustache.js

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)

like image 484
samccone Avatar asked Oct 09 '22 05:10

samccone


1 Answers

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:

<script id="template" class="template" type="text/x-mustache">
{{#a}}
<p>{{n}}</p>
{{/a}}
</script>

<h1>Output</h1>
<div id="output">
</div>
​

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.

like image 188
Jim Schubert Avatar answered Oct 12 '22 21:10

Jim Schubert