我刚刚在谷歌上搜索了“for循环”,但是看起来Velocity模板引擎只有“foreach”。
我该如何在Velocity模板中使用“for循环”?
只有 #foreach
。你需要在上下文中放置可迭代的东西。例如,使得一个名为bar
的数组或者Collection
可用:
#foreach ($foo in $bar)
$foo
#end
或者如果你想遍历一个数字范围:
#foreach ($number in [1..34])
$number
#end
$number
的值从1到34。 - Starwarswii想补充一点,在foreach循环内可以通过特殊的$foreach
属性来访问迭代信息:
#foreach ($foo in $bar)
count: $foreach.count
index: $foreach.index
first: $foreach.first
last: $foreach.last
#end
(上次我检查时,last
还存在一个错误)
$velocityCount
和$velocityHasNext
是可用的(http://velocity.apache.org/engine/releases/velocity-1.6/user-guide.html#Loops)。 - sendmoreinfo$foreach.parent.whatever
访问这些变量,例如 $foreach.parent.parent.index
可以在三重嵌套的 foreach 循环中获取外部循环的索引。 - Starwarswii在尝试循环列表时,我找到了解决方案。 将列表放入另一个类中,并为列表对象创建getter和setter。 例如:
public class ExtraClass {
ArrayList userList = null;
public ExtraClass(List l) {
userList = (ArrayList) l;
}
public ArrayList getUserList() {
return userList;
}
public void setUserList(ArrayList userList) {
this.userList = userList;
}
}
ExtraClass e = new ExtraClass(your list);
VelocityContext context = new VelocityContext();
context.put("data", e);
在模板中。#foreach ($x in $data.userList)
$x.fieldname //here $x is the actual obj inside the list
#end