4

I have this data structure:

flavors": {
            "sour": 0.16666666666666666,
            "salty": 0.16666666666666666,
            "sweet": 0,
            "meaty": 0.16666666666666666,
            "bitter": 0.16666666666666666
        }

My html is this:

<p>Flavors:</p>
   <ul>
     {{#Flavors}}
           <li>{{Flavours.Name}}</li>  // doesn't work  //
        {{/Flavors}}
     </ul>

What I'm trying to do is get at the name of the flavour: i.e. salty, sour, etc. I want to be able to cater for arbitrary values is the JSON, and not code them in the html block.

mike
  • 101
  • 1
  • 6

4 Answers4

12

You may iterate over the object in this way:

{{#each myObject}}
    Key: {{@key}} Value = {{this}}
{{/each}}

For details check this post: Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

Community
  • 1
  • 1
Slawomir Pasko
  • 785
  • 6
  • 14
  • I get an "uncaught exception error" Uncaught Error: Parse error on line 17: ...lavors}} Key: {{@key}} Value = {{thi ----------------------^ Expecting 'ID', got 'undefined' – mike Dec 11 '13 at 16:48
0

the answer to my question is on this page: Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

it's Ben's answer. Works very well indeed!

Community
  • 1
  • 1
mike
  • 101
  • 1
  • 6
-1

Iterate over json and use key to get property names.

for (var key in obj) {
   alert(' name=' + key + ' value=' + obj[key]);
   // do some stuff here
}
Sven
  • 303
  • 2
  • 12
-1

Your template should be like the following:

<p>Flavors:</p>
<ul>
 {{#each flavours}}
       <li>{{@key}}</li>
    {{/each}}
 </ul>

according with the documentation on the website.

MarcoL
  • 9,309
  • 3
  • 34
  • 50
  • The same error as above: Uncaught Error: Parse error on line 17: ...lavors}} Key: {{@key}} Value = {{thi ----------------------^ Expecting 'ID', got 'undefined' – mike Dec 11 '13 at 16:50
  • Not really clear here why this is down voted. It is exactly the same syntax as the accepted answer plus some HTML tags. – MarcoL May 07 '15 at 18:10