车把循环为属性赋值

Handlebars loop to assign value to attribute

我有长度是动态的数组值。但是我有 4 个图像支架。意味着如果数组的长度为 2,我将有 2 个填充支架和 2 个空支架。未填充的持有人将只是 div

我试过下面的代码,但这不符合我的需要,因为它会根据数组的长度生成 div

{{#each product.image}}
<div style="background-image:url(http://example.com/{{this}})"></div>
{{/each}}
<div></div>
<div></div>
<div></div>

如果你想要最多 4 个 div,用现有的数据填充,如果没有数据则留空,那么你可以使用自定义辅助函数:

Handlebars.registerHelper('times', function (index, options) {
        var result = '';
    for(var i = 0; i < 4; i++) {
       if(options.data.root.product.image[i]){
          result += '<div style="background-image:url(https://upload.wikimedia.org'+options.data.root.product.image[i]+')"></div>';
       } else {
          result += '<div>empty div</div>';
       }       
   }
   return result;
});

然后在你的 html:

{{#times this}}
{{/times}}

检查fiddle:fiddle