Iterate over an object for Handlebars?

Rey picture Rey · Sep 13, 2012 · Viewed 34.5k times · Source

So this is the general gist of my data (copied the look from chrome webkit inspector).

> Object
  > Fruit: Array[2]
    > 0: Object
       name: "banana"
       color: "yellow"
       animalthateats: "monkey"
       id: 39480
    > 1: Object
    length: 2
  > Vegetables: Array[179]
  > Dairy: Array[2]
  > Meat: Array[3]
  > __proto__: Object

And this is what I want to do (in general):

<select>
  <option value="">All Shows (default)</option>
  <optgroup label="Fruit">
    <option value="39480">Banana</option>
    <option value="43432">Strawberry</option>
  </optgroup>
  <optgroup label="Vegetables">
    <option value="3432">Broccoli</option>
  </optgroup>
</select>

I'm sorta new to the whole templating thing, and it definitely seems non-straightforward to accomplish... if I can use jQuery anyway that will work too, but preferably just with this setup.

Answer

ron picture ron · Dec 22, 2014

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>`

http://jsfiddle.net/rcondori/jfav4o6u/