admin管理员组

文章数量:1289933

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.

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.

Share Improve this question asked Dec 11, 2013 at 11:41 mikemike 1011 silver badge6 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 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?

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!

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
}

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.

本文标签: javascriptHow can I get the names of namevalue pairs in HandlebarsStack Overflow