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

10,083

Solution 1

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/

Solution 2

This works too:

{{#each this}}
<p>{{email}}</p>
{{/each}}
Share:
10,083

Related videos on Youtube

jmav
Author by

jmav

Web developer, multimedia engineer, JS &amp; jQuery guru

Updated on June 04, 2022

Comments

  • jmav
    jmav almost 2 years

    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}}
    
    • Andrew Miner
      Andrew Miner almost 10 years
      I'd recommend changing your accepted answer to Dave Stibrany's answer below. Definitely seems like the better way to do this.
  • MusikPolice
    MusikPolice over 10 years
    This works, but the answer from Dave Stibrany below is a much better solution.
  • Pallavi
    Pallavi almost 4 years
    where to specify the list