4

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.

Mircea Grelus
  • 2,905
  • 1
  • 20
  • 14

3 Answers3

10

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
  • 109,619
  • 77
  • 317
  • 330
  • 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 Jul 30 '10 at 08:16
  • @Mircea please see the update. All my examples are in Java, I hope NVelocity is not too different. – serg Jul 30 '10 at 15:08
  • 1
    +1 Nice `for` loop implementation. For `C#` you should use `get_item(i)` instead of `get(i)` and `Length` instead of `size()` (or `Count()` from linq). – Warlock Dec 11 '13 at 17:48
1

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...

Max Lambertini
  • 3,583
  • 1
  • 19
  • 24
0
Hashtable entries = new Hashtable(StringComparer.InvariantCultureIgnoreCase);
entries["listtool"] = new ListTool();
VelocityContext context = new VelocityContext(entries);

in listtool class you write your C# code to finish the fetch 2 dimensional array.

public Object get(Object list, int x,int  y)
    {
         return  ((IList)list)[x][y];
    }

$listtool.get($obj,x,y);
lonely7345
  • 11
  • 1