4

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.

Iladarsda
  • 10,640
  • 39
  • 106
  • 170

1 Answers1

8

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");
}
Julien Royer
  • 1,419
  • 1
  • 14
  • 27
  • - this approche works perfectly. Can you suggest a way on transforming the data to real array on client site? – Iladarsda Nov 15 '12 at 15:11
  • Many thanks! Slightly off topic, what is the purpose of 2nd parameter in `for loop`? – Iladarsda Nov 15 '12 at 15:16
  • 1
    It it just a fancy way to write `for (var i = 0; data[i]; ++i) { var drug = data[i]; …` – Julien Royer Nov 15 '12 at 15:20
  • @JulienRoyer its look like briliant solution but how about {{> next_more}} inside of collection template what is defined on gtihup pages https://github.com/janl/mustache.js/ – Nuri YILMAZ Jul 06 '18 at 18:41
  • @NuriYILMAZ don’t hesitate to create a new answer, mine is probably obsolete and I don’t know much about Mustache. :-) – Julien Royer Jul 20 '18 at 09:29