0

I would like to use the for loop in velocity template like below -

for(int i = 0; i < 10; i++){}

Any idea how to define in vm?

Thanks in advance

serg
  • 109,619
  • 77
  • 317
  • 330
Balaji
  • 859
  • 1
  • 16
  • 27

2 Answers2

1

Range Operator:

#foreach($i in [0..9])
    $i
#end
starwarswii
  • 2,187
  • 1
  • 16
  • 19
serg
  • 109,619
  • 77
  • 317
  • 330
0

Adding to serg's answer, if you want a zero-indexed loop but only have an exclusive end value (and don't want to subtract 1 with #set), you can use the builtin $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.

Let's say $n is 3.

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 will be [0, 1, 2, 3, 4].

See the user guide for more.

starwarswii
  • 2,187
  • 1
  • 16
  • 19