84

I’m new to Handlebars.js and just started using it. Most of the examples are based on iterating over an object. I wanted to know how to use handlebars in basic for loop.

Example.

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

How can this be achieved?

Jan Johansen
  • 1,999
  • 6
  • 30
  • 43
user1184100
  • 6,742
  • 29
  • 80
  • 121

5 Answers5

193

There's nothing in Handlebars for this but you can add your own helpers easily enough.

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 wanted a whole 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/

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • 1
    +1 for the helpers. As a side note, nesting the for helper won't work in scenarios where you need to refer back to the initial data. i.e data: { rows : 12, cols: 3}. – backdesk Mar 19 '14 at 15:55
  • 1
    When printing `{{../this}}` inside a nested `{{#times}}` block I've noticed that sometimes it will be `[Object object]` instead of the actual numer (one time per nested loop). – dude Mar 23 '18 at 10:05
  • @dude Do you have a runnable example of that? I haven't touched Handlebars for a couple years. – mu is too short Mar 23 '18 at 17:23
  • Inside the loop, I cannot retrieve data from handlebar, do you guys have any ideas about it? – HungDQ Apr 08 '19 at 02:06
  • @HungDQ Sorry but I don't know what you're trying to do, try asking a new question with all the necessary details. – mu is too short Apr 08 '19 at 02:48
  • @muistooshort I've created a new question with necessary details: https://stackoverflow.com/questions/55567260/handlebars-js-iterating-over-for-loop-using-handle-without-losing-data Thank you very much! – HungDQ Apr 08 '19 at 06:18
  • I'm getting `expected the second argument to be a number` error – Mahmoud Heretani Jan 19 '20 at 20:17
  • @MahmoudHeretani You're getting that error from what? Which line? – mu is too short Jan 19 '20 at 20:29
  • from the helper function line {{#times 10}} @muistooshort – Mahmoud Heretani Jan 19 '20 at 20:33
  • @MahmoudHeretani Which line of the helper? Can you reproduce the error at jsfiddle.net? – mu is too short Jan 19 '20 at 20:50
  • Is there a way to get the index of the loop? For example `{{this}}` – Longblog Mar 09 '22 at 22:28
  • 1
    @Longblog Sorry, haven't used Handlebars in years so I'm not sure. You could compute the index yourself given `this` and the loop's `from` and `incr` or perhaps call the `block.fn` with an object containing whatever you need. – mu is too short Mar 10 '22 at 01:52
26

Top answer here is good, if you want to use last / first / index though you could 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}}
Kannan J
  • 508
  • 5
  • 12
Mike Mellor
  • 1,316
  • 17
  • 22
  • 2
    This helper seems to not allow to use @../index or @../last when coming to nested uses of the Helper. Is this right or maybe I did something wrong? – madtyn Jun 13 '17 at 10:43
9

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}}
Manuel
  • 203
  • 2
  • 6
9

This snippet will take care of else block in case n comes as dynamic value, and provide @index optional context variable, it will keep the outer context of the execution as well.

/*
* 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;
});
dmi3y
  • 3,482
  • 2
  • 21
  • 32
  • 1
    I like this approach better because you have the @index variable at hand. Also you can easily add other variables depending on specific needs. – ChrisRich Jan 29 '16 at 10:15
8

Couple of years late, but there's now each available in Handlebars which allows you to iterate pretty easily over an array of items.

https://handlebarsjs.com/guide/builtin-helpers.html#each

Dharman
  • 30,962
  • 25
  • 85
  • 135
Sebastijan Dumančić
  • 1,165
  • 1
  • 11
  • 20