Iterating over the main for loop using Handlebars.js

Im new for Handlebars.js and just started using it. Most examples are based on iteration over an object. I would like to know how to use the rudders in the base for the loop.

Example.

for(i=0 ; i<100 ; i++) { create li with i as the value } 

How can this be achieved?

+60
Aug 12 2018-12-12T00:
source share
4 answers

There is nothing in Handlebars, but you can easily add your helpers.

If you just wanted to do something n times, then:

 Handlebars.registerHelper('times', function(n, block) { var accum = ''; for(var i = 0; i < n; ++i) accum += block.fn(i); return accum; }); 

and

 {{#times 10}} <span>{{this}}</span> {{/times}} 

If you need a solid for(;;) loop, then something like this:

 Handlebars.registerHelper('for', function(from, to, incr, block) { var accum = ''; for(var i = from; i < to; i += incr) accum += block.fn(i); return accum; }); 

and

 {{#for 0 10 2}} <span>{{this}}</span> {{/for}} 

Demo: http://jsfiddle.net/ambiguous/WNbrL/

+138
Aug 12 2018-12-12T00:
source share

The top answer here is good if you want to use last / first / index, although you can use the following

 Handlebars.registerHelper('times', function(n, block) { var accum = ''; for(var i = 0; i < n; ++i) { block.data.index = i; block.data.first = i === 0; block.data.last = i === (n - 1); accum += block.fn(this); } return accum; }); 

and

 {{#times 10}} <span> {{@first}} {{@index}} {{@last}}</span> {{/times}} 
+10
Jan 04 '17 at 12:00
source share

If you like CoffeeScript

 Handlebars.registerHelper "times", (n, block) -> (block.fn(i) for i in [0...n]).join("") 

and

 {{#times 10}} <span>{{this}}</span> {{/times}} 
+7
Jan 25 '14 at 8:14
source share

This snippet will take care of another block, if n appears as a dynamic value and provides an optional context variable @index , it will also preserve the external execution context.

 /* * Repeat given markup with given times * provides @index for the repeated iteraction */ Handlebars.registerHelper("repeat", function (times, opts) { var out = ""; var i; var data = {}; if ( times ) { for ( i = 0; i < times; i += 1 ) { data.index = i; out += opts.fn(this, { data: data }); } } else { out = opts.inverse(this); } return out; }); 
+4
Sep 03 '15 at 21:45
source share



All Articles