Handlebars Loop To Assign Value To Attribute

- 1 answer

I have values of array which the length is dynamic. But I have image holder of 4. Means If the length of the array is 2, I will have 2 filled holder and left 2 empty holder. The unfilled holder will be simply div

I've tried with below code but that doesn't suite my needs, because it will produce the div according to the length of the arrays.

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


If you want max number of 4 divs, filled up with data that is there and left empty if no data than you can use a custom helper function:

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

and then in your html:

{{#times this}}

Check fiddle: fiddle