【问题标题】:mustache template to work with an object having series of named objects用于处理具有一系列命名对象的对象的 mustache 模板
【发布时间】:2014-02-27 20:48:33
【问题描述】:

需要以下模板的帮助来整理给定的 json 数据。里面的每个对象都是另一个命名对象,有没有办法简单地遍历列表。

目前还没有找到处理这种情况的例子。请帮忙。

{
"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
}
}

模板是

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

脚本是

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

【问题讨论】:

    标签: javascript templates template-engine mustache


    【解决方案1】:

    您需要在将值传递给 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});
    

    【讨论】:

      猜你喜欢
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 2023-03-14
      • 2017-02-07
      • 1970-01-01
      • 2020-05-01
      • 1970-01-01
      相关资源
      最近更新 更多