How to iterate over array in handlebar template without defined name in model
Asked Answered
C

2

17

I have model:

[
  {
    "ID": 5,
    "email": "[email protected]"
  },
  {
    "ID": 6495,
    "email": "[email protected]"
  }
]

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": "[email protected]"
      },
      {
        "ID": 6495,
        "email": "[email protected]"
      }
    ]

I would simple iterate in handlebars like:

   {{#each users}}
    <p>{{email}}</p>
   {{/each}}
Castaneda answered 27/7, 2012 at 3:51 Comment(1)
I'd recommend changing your accepted answer to Dave Stibrany's answer below. Definitely seems like the better way to do this.Delitescent
M
16

If you have this:

var a = [
  {
    "ID": 5,
    "email": "[email protected]"
  },
  {
    "ID": 6495,
    "email": "[email protected]"
  }
];

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/

Massasoit answered 27/7, 2012 at 4:23 Comment(1)
This works, but the answer from Dave Stibrany below is a much better solution.Aerodonetics
H
34

This works too:

{{#each this}}
<p>{{email}}</p>
{{/each}}
Hager answered 26/6, 2013 at 20:20 Comment(1)
where to specify the listAquifer
M
16

If you have this:

var a = [
  {
    "ID": 5,
    "email": "[email protected]"
  },
  {
    "ID": 6495,
    "email": "[email protected]"
  }
];

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/

Massasoit answered 27/7, 2012 at 4:23 Comment(1)
This works, but the answer from Dave Stibrany below is a much better solution.Aerodonetics

© 2022 - 2024 — McMap. All rights reserved.