简体   繁体   中英

Iterating through objects in Handlebars

I have a JavaScript object that looks like this:

{
    "key1": {
        name: "SomeName1"
    },
    "key2": {
        name: "SomeName2"
    },
    "key3": {
        name: "SomeName3"
    }
}

I am passing this into my handlebars template. I want to display all the names on the screen.

app.get('/', function(req, res) {
    res.render('index', {
        data: myObject
    });
});

In my index.hbs file, I have:

{{#each data}}
    Name: {{this.name}}
    <br>
{{/each}}

For now, its just displaying

Name:
Name:
Name:

for your code to work your object needs to look something like this

{
  data:[
    { name: '1'},
    { name: '2'},
    { name: '3'}
  ]
}

or literate through object keys like this

{{#each this}}
   {{#each this}}
         Name: {{this}}
         <br>
   {{/each}}
{{/each}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM