Mustache.js loop through JSON data

丶灬走出姿态 提交于 2019-12-05 01:59:26

问题


Can anyone advise how should my template loop like to loop through JSON data in following example?
DEMO here: http://jsfiddle.net/Seefeld/LbVEH/

 {
    "0": {
        "Dosage": "25",
        "Drug": "Indocin",
        "Patient": "David",
        "Date": "15/11/2012 14:29:14"
    },
    "1": {
        "Dosage": "50",
        "Drug": "Enebrel",
        "Patient": "Sam",
        "Date": "15/11/2012 14:29:14"
    },
    "2": {
        "Dosage": "10",
        "Drug": "Hydralazine",
        "Patient": "Christoff",
        "Date": "15/11/2012 14:29:14"
    },
    "3": {
        "Dosage": "21",
        "Drug": "Combivent",
        "Patient": "Janet",
        "Date": "15/11/2012 14:29:14"
    },
    "4": {
        "Dosage": "100",
        "Drug": "Dilantin",
        "Patient": "Melanie",
        "Date": "15/11/2012 14:29:14"
    }
}

All examples I have seen on mustache.js assumed that you know the object name. Any suggestion much appreciated.


回答1:


You can either transform data into a genuine array (which it should be anyway):

var drugs = [];
for (var i = 0, drug; (drug = data[i]); ++i) {
  drugs.push(drug);
}

var template = "{{#drugs}}<p>{{Drug}}</p>{{/drugs}}";
var html = Mustache.to_html(template, {drugs: drugs});
$(html).appendTo("#cnt");

or browse the data yourself:

var template = "<p>{{Drug}}</p>";
for (var i = 0, drug; (drug = data[i]); ++i) {
  var html = Mustache.to_html(template, drug);
  $(html).appendTo("#cnt");
}


来源:https://stackoverflow.com/questions/13399816/mustache-js-loop-through-json-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!