mike
mike

Reputation: 101

How can I get the names of name-value pairs in Handlebars?

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.

Upvotes: 4

Views: 4653

Answers (4)

mike
mike

Reputation: 101

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!

Upvotes: 0

MarcoL
MarcoL

Reputation: 9989

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.

Upvotes: -1

Slawomir Pasko
Slawomir Pasko

Reputation: 907

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?

Upvotes: 12

Sven
Sven

Reputation: 303

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
}

Upvotes: -1

Related Questions