Balaji
Balaji

Reputation: 869

For loop in velocity template

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

Upvotes: 0

Views: 1640

Answers (2)

serg
serg

Reputation: 111265

Range Operator:

#foreach($i in [0..9])
    $i
#end

Upvotes: 1

starwarswii
starwarswii

Reputation: 2417

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.

Upvotes: 0

Related Questions