Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 919
summerbulb Avatar asked Oct 21 '11 09:10

summerbulb


People also ask

What is Velocityengine in Java?

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.

How do you comment in a Velocity template?

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.

What is $velocityCount?

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.

What is velocity .VM file?

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.


2 Answers

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.

like image 142
serg Avatar answered Oct 13 '22 12:10

serg


#set($i = 0)

  #foreach($str in $names)
    #set($i = $i+1)
    $i : $str
 #end
like image 23
Dhiral Pandya Avatar answered Oct 13 '22 14:10

Dhiral Pandya