6

With dot.js template engine how do you loop through an object? In the example data below how do you loop through the "msg" object?

{
    "msg": {
        "1": {
            "a": "a1"
        },
        "2": {
            "b": "b2"
        }
    }
}
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
user3658423
  • 1,904
  • 5
  • 29
  • 49

2 Answers2

9

From the example on the website, it looks as if you should be able to do:

{{ for(var prop in it) { }}
<div>{{=prop}}</div> <!-- Prints "msg" -->
    {{ for(var msgProp in it[prop]) { }}
    <div>{{=msgProp}}</div> <!-- Prints "1" and "2" -->
        {{ for(var numProp in it[prop][msgProp]) { }}
        <!-- Prints "a: a1" and "b: b1" -->
        <div>{{=prop}}: {{=it[prop][msgProp][numProp]}}</div>
        {{ } }}
    {{ } }}
{{ } }}

However you may want to simplifiy that object a little bit with Javascript first, before passing it to the template in order to make it easier to iterate.

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • 2
    I've found it slightly more readable (though I guess less interoperable with older browsers) to instead use Object.keys. Cuts down on all the weird bracket nesting. So something like `{{~Object.keys(it) :firstGroup}}... {{~}}` – Fabio Beltramini Oct 22 '15 at 21:06
0

The best thing to do would be to first convert msg to an array. It's much easier to iterate that way. After that, just use jQuery's $.each().

yonas
  • 815
  • 7
  • 4