Foreach Loop
The #foreach
element allows for looping. For example:
<ul>
#foreach( $product in $allProducts )
<li>$product</li>
#end
</ul>
This #foreach
loop causes the $allProducts
list
(the object) to be looped over for all of the products (targets) in the list. Each
time through the loop, the value from $allProducts
is placed into
the $product
variable.
The contents of the $allProducts
variable is a Vector, a Hashtable
or an Array. The value assigned to the $product
variable is a Java
Object and can be referenced from a variable as such. For example, if
$product
was really a Product class in Java, its name could be
retrieved by referencing the $product.Name
method
($Product.getName()
).
Lets say that $allProducts
is a Hashtable. If you wanted to retrieve
the key values for the Hashtable as well as the objects within the Hashtable, you
can use code like this:
<ul>
#foreach( $key in $allProducts.keySet() )
<li>Key: $key -> Value: $allProducts.get($key)</li>
#end
</ul>
Velocity 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>$velocityCount</td><td>$customer.Name</td></tr>
#end
</table>
Velocity also now provides an easy way to tell if you are on the last iteration of a loop:
#foreach( $customer in $customerList )
$customer.Name#if( $velocityHasNext ),#end
#end
The default name for the "has next" variable reference, which is specified in the velocity.properties file, is $velocityHasNext. The default name for the loop counter variable reference, which is specified in the velocity.properties file, is $velocityCount. By default the counter starts at 1, but this can be set to either 0 or 1 in the velocity.properties file. Here's what the loop counter properties section of the velocity.properties file appears:
# Default name of the loop counter
# variable reference. directive.foreach.counter.name = velocityCount
directive.foreach.iterator.name = velocityHasNext
# Default starting value of the loop
# counter variable reference. directive.foreach.counter.initial.value = 1
It is possible to set a maximum allowed number of times that a loop may be run. By default there is no max (indicated by a value of 0 or less), but this can be set to an arbitrary number in the velocity.properties file. This is useful as a fail-safe.
# The maximum allowed number of loops. directive.foreach.maxloops = -1
If you want to stop looping in a foreach from within your template, you can now use the #break directive to stop looping at any time:
## list first 5 customers only
#foreach( $customer in $customerList )
#if( $velocityCount > 5 )
#break
#end
$customer.Name
#end