Search code examples
node.jsexpressswig-template

How to repeat a block of code X number of times in swig template (expressjs)


I am using swig templates with expressjs and trying to do something that is probably really simple, but I have been unable to find an example anywhere.

I have a variable containing a number, FOO.

I then have a block of code I want to repeat FOO times.

in node I would do this:

var FOO=5;
for(var counter=1;counter<FOO;counter++)
{
    console.log('This is line #' + counter);
}

In swig there is the {% for X in Y %} method but that requires an array to iterate through. What I want is something that will simply count from 1 (or 0) to FOO and repeat a block of code for each one.

It seems like it should be the simplest thing to do but I just cannot seem to find any examples. Any pointers would be very much appreciated.

James


Solution

  • Here's a silly trick:

    {% for i in Array.prototype.constructor.call(null, FOO) %}
      {{ loop.index }}.
    {% endfor %}
    

    Where loop.index is your counter (1-based, use loop.index0 if you want 0-based).