Search code examples
javascripttemplatestemplate-enginemustache

mustache template to work with an object having series of named objects


Need help with the following template to sort out the given json data. each object inside is another named object, is there a way to simply iterate through the list.

so far unable to find an example that deals with this case. Kindly help.

{
"6gb1": {
    "id": "b7e3b34b-7f15-4221-9601-69899a29c738",
    "productId": "6gb1",
    "title": "Social Studies",
    "folioNumber": "1",
    "publicationDate": "2014-01-10T05:00:00.000Z",
    "targetDimensions": ["1024x768"],
    "folioDescription": "Social Studies",
    "manifestXRef": "Social Studies",
    "previewImageURL": "",
    "isFree": true
},
"5gb2": {
    "id": "65017770-bd01-47a2-867b-46948ea58d4c",
    "productId": "5gb2",
    "title": "Algebra",
    "folioNumber": "1",
    "publicationDate": "2014-01-10T05:00:00.000Z",
    "targetDimensions": ["1024x768"],
    "folioDescription": "Algebra",
    "manifestXRef": "Algebra",
    "previewImageURL": "",
    "isFree": true
},
"5gb1": {
    "id": "b1148439-1b18-4b63-8d92-b3a4051286af",
    "productId": "5gb1",
    "title": "English",
    "folioNumber": "1",
    "publicationDate": "2014-01-10T05:00:00.000Z",
    "targetDimensions": ["1024x768"],
    "folioDescription": "English",
    "manifestXRef": "English",
    "previewImageURL": "",
    "isFree": true
},
"6gb2": {
    "id": "0199ac64-3f20-45f9-ba70-883f95ab0e58",
    "productId": "6gb2",
    "title": "Environmental Science",
    "folioNumber": "1",
    "publicationDate": "2014-01-10T05:00:00.000Z",
    "targetDimensions": ["1024x768"],
    "folioDescription": "Environmental Science",
    "manifestXRef": "Environmental Science",
    "previewImageURL": "",
    "isFree": true
}
}

and the template is

<script id="folioTemplate" type="text/template">
{{#folios}}
<li class='folio clearfix'>
     {{folioDescription}}
    <div id='title'>{{{title}}}</div>
</li>
{{/folios}}
</script>

and the script is

document.getElementById("folios").innerHTML = Mustache.render(document.getElementById('folioTemplate').innerHTML, {'folios': folios});

Solution

  • You need to prepare your values before passing them to Mustache:

    var values = [];
    for (var key in folios) {
      if (Object.prototype.hasOwnProperty.call(folios, key)) {
        values.push(folios[key]);
      }
    }
    
    var tpl = document.getElementById('folioTemplate').innerHTML;
    document.getElementById("folios").innerHTML = Mustache.render(tpl, {'folios': values});