javascript - 使用 Handlebars 渲染对象的嵌套数组

标签 javascript node.js handlebars.js

我在渲染 hbs 中的嵌套对象数组时遇到问题。

我需要在网页上一起显示每个图像及其相应的链接(例如:图像“1”有一个链接“a”)。

下面的代码不起作用,有其他解决方案吗?

服务器.js:

res.render('index.hbs', {

    images: [ 1, 2, 3],

    links: [a, b, c] 

   }

);

索引.hbs:

{{#each images}}

     {{#each links}}

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

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

     {{/each}}           

{{/each}}

最佳答案

您可以重新排列输入以仅使用一个数组:

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);

然后你可以轻松地迭代它:

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

您可以看到这段代码正在运行 here .

关于javascript - 使用 Handlebars 渲染对象的嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49102971/

相关文章:

mysql - Handlebars js 不呈现 mysql 查询返回的对象数组(在 nodejs 服务器中)

javascript - 尝试访问 SVG 元素时 getElementById 返回 null

node.js - Node-Orm hasOne 关系未正确形成

node.js - Mongoose 仅​​使用 createdAt 时间戳

node.js - 垃圾收集器什么时候释放 'request' 对象?

jQuery 事件不会在 Handlebars 模板上触发

javascript - 通过 state.value ReactJS 将 textarea 值复制到新组件

javascript - 我可以用 python + selenium Hook phantomjs 跳转到新网站的事件吗?

javascript - Angular 三级嵌套网址

javascript - Handlebars 动态内联部分