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.
The Apache Velocity Engine is a free open-source templating engine. Velocity permits you to use a simple yet powerful template language to reference objects defined in Java code. It is written in 100% pure Java and can be easily embedded into your own applications.
Like the Java programming language, Velocity has single-line and block comments. A single line comment begins with ## and finishes at the end of the line. This is an example of a single line comment in VTL: ## This is a single line comment.
The default name for the loop counter and its starting value is specified through runtime properties. By default it starts at 1 and is called $velocityCount . # Default name of the loop counter # variable reference.
Velocity is a Java-based templating engine. It's an open source web framework designed to be used as a view component in the MVC architecture, and it provides an alternative to some existing technologies such as JSP. Velocity can be used to generate XML files, SQL, PostScript and most other text-based formats.
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.
#set($i = 0)
#foreach($str in $names)
#set($i = $i+1)
$i : $str
#end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With