views:

67

answers:

1

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.

+2  A: 

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
serg
It isn't working.It complains about the "[" character in you second line: "$testArray[0].size()".And when I try to get the value of a specific array element like $testArray[1][1], it displays: System.String[][][1][1]. So apparently that syntax is not recognized.
Mircea Grelus
@Mircea please see the update. All my examples are in Java, I hope NVelocity is not too different.
serg