Iterate over an object for Handlebars? [duplicate]
use just "this"
`<script id="some-template" type="text/x-handlebars-template"><option value="none">Selec</option>{{#each data}} <optgroup label="{{@key}}"> {{#each this}} <option value="{{id}}">{{name}}</option> {{/each}} </optgroup>{{/each}}</script>`
Your current data format presents you with two problems:
- Handlebars really wants to iterate over arrays, not objects.
- JavaScript objects have no reliable order.
You'll have better luck if you can rearrange your data to be nested arrays, something like this:
var foods = { /* what you already have */ };var for_hb = [ { name: 'Fruit', foods: foods.Fruit }, { name: 'Vegetables', foods: foods.Vegetables }, //...];
You can do that with something simple like this:
var for_hb = [ ];for(var k in foods) for_hb.push({name: k, foods: foods[k]});for_hb.sort(function(a, b) { a = a.name.toLowerCase(); b = b.name.toLowerCase(); return a < b ? -1 : a > b ? +1 : 0;});var html = compiled_template({ groups: for_hb });
Then your template is simple:
<select> <option value="">All Shows (default)</option> {{#each group}} <optgroup label="{{name}}"> {{#each foods}} <option value="{{id}}">{{name}}</option> {{/each}} {{/each}}</select>
You could write a helper to iterate over an object but you'd still have to specify the keys in an array if you wanted to be sure of a sensible display order.
You can do this via a custom component see example, this is not supported by our default {{each}}
helper (and that is intentional).
Sample Data:
a = {a:'muhammad', b :'asif', c: 'javed', username: 'maxifjaved'}
**
Online Demo for iterate throw an Object
**