Does NVelocity support #for loops? I've looked through the documentation and all I could find was the #foreach loop.
I want to loop over a 2 dimensional array.
Does NVelocity support #for loops? I've looked through the documentation and all I could find was the #foreach loop.
I want to loop over a 2 dimensional array.
You can use range operator [n..m]
in foreach loop to emulate normal loop. You can also access multidimensional array elements in a usual way like $array[n][m]
.
For example if you have such 2d array (sorry for Java code):
String[][] testArray = new String[][] {{"a1","b1"},{"a2","b2"},{"a3","b3"}};
You can loop through it in Velocity like this:
#set($sizeX = $testArray.size() - 1)
#set($sizeY = $testArray[0].size() - 1)
#foreach($i in [0..$sizeX])
#foreach($j in [0..$sizeY])
e[$i][$j] = $testArray[$i][$j] <br/>
#end
#end
Which outputs:
e[0][0] = a1
e[0][1] = b1
e[1][0] = a2
e[1][1] = b2
e[2][0] = a3
e[2][1] = b3
UPDATE:
Apparently bracketed syntax was introduced only in Velocity 1.7b1 according to changelog. In older versions we would just need to replace brackets with get(i)
as arrays in Velocity are backed by ArrayList
(in Java). So, this should work:
#set($sizeX = $testArray.size() - 1)
#set($sizeY = $testArray.get(0).size() - 1)
#foreach($i in [0..$sizeX])
#foreach($j in [0..$sizeY])
e[$i][$j] = $testArray.get($i).get($j) <br/>
#end
#end