40

I already posted a similar question a week ago on How to use 'for' loop in velocity template?.

So...basically I can't use 'for' loop in a velocity template.

Let's say I have a variable that holds integer 4. I want to display something four times using that variable. How do I do it in a velocity template?

Community
  • 1
  • 1
Moon
  • 22,195
  • 68
  • 188
  • 269

3 Answers3

63

Try to do it like this:

#set($start = 0)
#set($end = 4)
#set($range = [$start..$end])
#foreach($i in $range)
   doSomething
#end

The code has not been tested, but it should work like this.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
csupnig
  • 3,327
  • 1
  • 24
  • 22
40

You don't have to use the #set like the accepted answer. You can use something like this:

#foreach($i in [1..$end])
    LOOP ITERATION: $i
#end

If you want zero indexed you do have to use one #set because you can't subtract one within the range operator:

#set($stop = $end - 1)
#foreach($i in [0..$stop])
    LOOP ITERATION: $i
#end
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
  • That second one doesn't work. You can't inline a -1 in a range operator. You'd have to `#set($foo = $end - 1)` first, then use `#foreach($i in [0..$foo])` – starwarswii Jul 21 '17 at 15:22
  • I just submitted an edit. `#set($stop=$end-1)` doesn't work, and `$stop` remains null. Spaces matter in Velocity. To correctly assign it, use `#set($stop = $end - 1)` or `#set($stop=$end - 1)`. `#set($stop=$end -1)` is also invalid – starwarswii Jul 21 '17 at 15:30
6

Just to add another option to Stephen Ostermiller's answer, you can also create a zero-indexed loop using $foreach.index. If you want to loop $n times:

#foreach($unused in [1..$n])
    zero indexed: $foreach.index
#end

here, $unused is unused, and we instead use $foreach.index for our index, which starts at 0.

We start the range at 1 as it's inclusive, and so it will loop with $unused being [1, 2, 3, 4, 5], whereas $foreach.index is [0, 1, 2, 3, 4].

See the user guide for more.

starwarswii
  • 2,187
  • 1
  • 16
  • 19