Velocity and $foreach.count
Solution 1
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
Solution 2
Neither $foreach.count
nor $counter
worked for me.
This answer suggests using $velocityCount
, and it worked for me.
Solution 3
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
Solution 4
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.
Solution 5
k.honsalis answer is deprecated.
At this point you can only use $velocityCount, even though the documentation will refer to deprecated methods.
#foreach($item in $items)
counter 0: $foreach.index
counter 1: $foreach.count
counter 2: $counter
counter 3: $velocityCount
#end
Output:
$foreach.index
$foreach.count
$counter
1
Related videos on Youtube
Comments
-
yannisf almost 2 years
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?
-
AlikElzin-kilaka about 5 yearscan you please add the complete foreach statement?
-
-
Dave G over 12 yearsIn Velocity < 1.7 there was a way to configure the name of the counter variable using "directive.foreach.counter.name = velocityCount" in the properties that initialized the engine (this was from the default version). It looks like they've removed the ability to do that change and have named it specifically ${foreach.counter}.
-
Dave G over 12 yearsI'm used to using the formal notation ... a little more verbose but for the most part exposing clarity.
-
Sariq Shaikh almost 9 yearsThis worked for me too. We are using velocity 1.5 and due to using third party framework we can not move to 1.7
-
kscoder over 4 yearsI am using velocity engine 2.1 and ${foreach.count} works.
-
ewaolx over 4 yearsThis answer makes more sense. Thanks!