I am using velocity 1.7 and within a foreach loop I want to print the count. In the template I have the following string in a #foreach/#end section:
Count: $foreach.count
and was expecting to see in the rendered result something like
Count: 1
...
Count: 2
...
but all I see is:
Count: $foreach.count
...
Count: $foreach.count
...
Any ideas what am I doing wrong?
Velocity can be used to generate web pages, SQL, PostScript and other output from templates. It can be used either as a standalone utility for generating source code and reports, or as an integrated component of other systems.
Neither $foreach.count
nor $counter
worked for me.
This answer suggests using $velocityCount
, and it worked for me.
Your code is partial, we don't see the foreach directive.
Else, I know that the foreach loop has a built-in variable called $counter
, though in the guide they do refer to $foreach.count
I tried with $counter
& $foreach.count
but neither of these worked for me.
However, the $velocityCount
tag worked and below is the example.
Input code:
#foreach($entry in $entries)
<p>In for Loop count is : $velocityCount</p>
#end
Output:
In for Loop count is : 1
In for Loop count is : 2
In for Loop count is : 3
I do not know why the foreach loop built-in variable called $count is not working as guide refer. But $velocityCount is worked for me.
There is property called directive.foreach.counter.name is velocityCount in velocity.properties file, so default $count variable may not be working.
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