user1937434
user1937434

Reputation: 349

Apache Velocity - Parse VM file Based Upon Total Foreach Count

I am trying to create an Apache Velocity Script that executes a VM file based upon a foreach count of 1 or 2 respectively.

Here is the code that I am using:

#set ($i = 0)
#foreach ($report in $reportInfo.reportList)
#set ($i = $i + 1)
#if ($i == 2)
#parse ("/MyReport/Report1.vm")
#end
#end

#set ($j = 0)
#foreach ($Report in $reportInfo.reportlist)
#set ($j = $j + 1)
#if ($j == 1 )
#parse ("/MyReport/Report2.vm")
#end
#end

What ends up happening is that if there is a foreach total of 2, it will also run Report2.vm since the count is "1 2". Is there anyway that I can code this to look at either the sum, max, or total of the count for my variables?

Upvotes: 0

Views: 1966

Answers (2)

Perception
Perception

Reputation: 80633

Sounds to me like you just want to perform some logic based off the size of the list.

#if ($reportInfo.reportList.size() == 1)
#parse ("/MyReport/Report2.vm")
#elseif ($reportInfo.reportList.size() == 2)
#parse ("/MyReport/Report1.vm")
#end

Upvotes: 1

Mrugen Deshmukh
Mrugen Deshmukh

Reputation: 249

Hi I understand that you would like to count how many times your 'for-each' loop has been executing, apache velocity templating engine provides an easy way to get the loop counter so that you can do something like the following:

<table>
#foreach( $customer in $customerList )
<tr><td>$foreach.count</td><td>$customer.Name</td></tr>
#end
</table>

Velocity also has other convenience counters like:
1. $foreach.index instead of $foreach.count
2. $foreach.hasNext
3. $foreach.first and $foreach.last are also provided to compliment $foreach.hasNext

Please refer Apache Velocity user guide for more examples.

Upvotes: 0

Related Questions