How to get a zero-based count in a Velocity foreach loop

summerbulb picture summerbulb · Oct 21, 2011 · Viewed 20.8k times · Source

I am trying to get a zero-based counter in a Velocity #foreach directive.

if i use:

#foreach ($item in $list)
   item.getName() : $velocityCount
#end

i will get:

Fred : 1
Wilma : 2
Barney : 3

But i need:

Fred : 0
Wilma : 1
Barney : 2

The solution must be as simple as possible from the velocity template's point of view.

EDIT:
I can use:

#foreach ($item in $list)
   #set( $num = $velocityCount - 1 ) //The white space in mandatory
   item.getName() : $num
#end

and it works. But I'm looking for a more elegant solution.

EDIT 2:
I need the one-based counter to be available too. That is, in the same template i will most likely have one #foreach directive that will require a zero-based counter and another #foreach directive that requires a one-base counter.

Answer

serg picture serg · Oct 21, 2011

If you are using Velocity 1.7 there are $foreach.index (0-based) and $foreach.count (1-based) special vars available inside loops.

$velocityCount is something that was deprecated long time ago afaik.