简体   繁体   English

使用把手渲染对象的嵌套数组

[英]Rendering nested arrays of objects using handlebars

I am having trouble rendering nested arrays of objects within hbs. 我在渲染hbs中的嵌套对象数组时遇到麻烦。

I need to display every images and their corresponding links together on a webpage (example: Image "1" have a link of "a"). 我需要在网页上一起显示每个图像及其相应的链接(例如:图像“ 1”的链接为“ a”)。

Below code does not work, is there any other solution for that? 下面的代码不起作用,还有其他解决方案吗?

Server.js: Server.js:

res.render('index.hbs', {

    images: [ 1, 2, 3],

    links: [a, b, c] 

   }

);

index.hbs: 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 . 您可以在这里看到这段代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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