NVelocity是否支持#for循环?我已经浏览了文档,我所能找到的就是#foreach循环。
我想循环遍历一个二维数组。
发布于 2010-07-29 17:53:41
您可以在foreach循环中使用范围运算符[n..m]
来模拟普通循环。您还可以通过通常的方式访问多维数组元素,如$array[n][m]
。
例如,如果您有这样的2d数组(对不起,Java代码):
String[][] testArray = new String[][] {{"a1","b1"},{"a2","b2"},{"a3","b3"}};
你可以像这样在Velocity中遍历它:
#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
以下哪项输出:
e[0][0] = a1
e[0][1] = b1
e[1][0] = a2
e[1][1] = b2
e[2][0] = a3
e[2][1] = b3
更新
显然,根据changelog,仅在Velocity 1.7b1中引入了括号语法。在老版本中,我们只需要用get(i)
替换括号,因为Velocity中的数组是由ArrayList
(Java语言)支持的。因此,这应该是可行的:
#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
发布于 2011-11-08 13:25:40
遗憾的是,NVelocity“原样”不支持for循环,只支持foreach。即使是Castle Project's fork也只改进了foreach循环。
对于.NET项目来说,NVelocity走进了死胡同。我们在我们的项目中使用它,使用与lonely7345相似的代码来解决它的缺点,我们一直在使用它,因为直到最近,还没有更好或更容易的.net模板引擎。
然而,我们是considering using Razor as a Standalone templating engine..。
发布于 2011-10-16 03:45:10
Hashtable entries = new Hashtable(StringComparer.InvariantCultureIgnoreCase);
entries["listtool"] = new ListTool();
VelocityContext context = new VelocityContext(entries);
在listtool类中,您可以编写C#代码来完成获取二维数组。
public Object get(Object list, int x,int y)
{
return ((IList)list)[x][y];
}
$listtool.get($obj,x,y);
https://stackoverflow.com/questions/3364451
复制相似问题