"for" loop in velocity template

48,741

Solution 1

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.

Solution 2

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

Solution 3

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.

Share:
48,741
Moon
Author by

Moon

Updated on September 08, 2020

Comments

  • Moon
    Moon almost 4 years

    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?