Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop in NVelocity

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.

like image 266
Mircea Grelus Avatar asked Dec 23 '22 00:12

Mircea Grelus


2 Answers

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
like image 62
serg Avatar answered Jan 09 '23 16:01

serg


Alas, NVelocity "as is" does not support for loops, only foreach. Even Castle Project's fork improves only foreach loop.

AFAIK, for .NET projects NVelocity is on a dead-end. We are using it in our projects, using code not unlike lonely7345 to address its shortcomings, and we kept using it because, until recently, there was no better or easier templating engine for .net.

However, we are considering using Razor as a Standalone templating engine...

like image 36
Max Lambertini Avatar answered Jan 09 '23 17:01

Max Lambertini