17

I have model:

[
  {
    "ID": 5,
    "email": "xx@vflbg.com"
  },
  {
    "ID": 6495,
    "email": "email@monkey.com"
  }
]

Code for iterating in handlebars:

   {{#each xxx}}
    <p>{{email}}</p>
   {{/each}}

how do I define xxx ?

If JSON had name in model like:

   users: [
      {
        "ID": 5,
        "email": "xx@vflbg.com"
      },
      {
        "ID": 6495,
        "email": "email@monkey.com"
      }
    ]

I would simple iterate in handlebars like:

   {{#each users}}
    <p>{{email}}</p>
   {{/each}}
jmav
  • 3,119
  • 4
  • 27
  • 27
  • 2
    I'd recommend changing your accepted answer to Dave Stibrany's answer below. Definitely seems like the better way to do this. – Andrew Miner Jun 02 '14 at 20:22

2 Answers2

34

This works too:

{{#each this}}
<p>{{email}}</p>
{{/each}}
Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
Dave Stibrany
  • 2,369
  • 3
  • 21
  • 21
16

If you have this:

var a = [
  {
    "ID": 5,
    "email": "xx@vflbg.com"
  },
  {
    "ID": 6495,
    "email": "email@monkey.com"
  }
];

Then just supply the desired name when you call the compiled template:

var t = Handlebars.compile($('#t').html());
var h = t({ users: a });

That will leave you with your desired HTML in h.

Demo: http://jsfiddle.net/ambiguous/ZgVjz/

If you have a collection built from the data:

var c = new C(a);

Then you'd call the template like this:

var h = t({ users: c.toJSON() });

Demo: http://jsfiddle.net/ambiguous/uF3tj/

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • 3
    This works, but the answer from [Dave Stibrany](http://stackoverflow.com/users/546741/dave-stibrany) [below](http://stackoverflow.com/a/17329692/591374) is a much better solution. – MusikPolice Nov 27 '13 at 18:43