"for" loop in velocity template
I already posted a similar question a week ago o开发者_JAVA技巧n 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?
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.
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
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.
精彩评论