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

981 views Asked by At

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

2

There are 2 answers

0
robertklep On BEST ANSWER

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).

0
Dan Tello On

This also works:

{% for i in Array(x) %}
  {{ loop.index }} 
{% endfor %}

Where x is the number of times to loop. Calling the constructor didn't in my case for whatever reason.