Ad

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(http://example.com/{{this}})"></div>
{{/each}}
<div></div>
<div></div>
<div></div>
Ad

Answer

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++) {
       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 {
          resul     } else {
          result += '<div>empty div</div>';
       }       
   }
   return result;
});

and then in your html:

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

Check fiddle: fiddle

Ad
source: stackoverflow.com
Ad