简体   繁体   中英

Rendering nested arrays of objects using handlebars

I am having trouble rendering nested arrays of objects within hbs.

I need to display every images and their corresponding links together on a webpage (example: Image "1" have a link of "a").

Below code does not work, is there any other solution for that?

Server.js:

res.render('index.hbs', {

    images: [ 1, 2, 3],

    links: [a, b, c] 

   }

);

index.hbs:

{{#each images}}

     {{#each links}}

          <img> {{this}} </img> // should display all images

          <a> {{this}} </a> // should display all links

     {{/each}}           

{{/each}}

You can rearrange your input to work with only one array:

var images = [1, 2, 3];
var links = ['a', 'b', 'c'];
var objects = []; 
for (var i = 0; i < images.length; i ++) { 
    objects[i] = { image: images[i], link: links[i] }; 
}

var data = { objects: objects };

res.render('index.hbs', data);

Then you can iterate over it easily:

{{#each objects}}
    <img> {{image}} </img> // should display all images
    <a> {{link}} </a> // should display all links
{{/each}}

You can see this chunk of code working here .

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