Moo*_*oon 23 java templates velocity
我只是用google搜索'for loop',但看起来速度只有'foreach'.
如何在力度模板中使用"for loop"?
ser*_*erg 38
想要在foreach循环中添加迭代信息,可以从特殊$foreach
属性访问:
#foreach ($foo in $bar)
count: $foreach.count
index: $foreach.index
first: $foreach.first
last: $foreach.last
#end
Run Code Online (Sandbox Code Playgroud)
(我上次检查时last
包含了一个bug)
Whi*_*g34 34
只有#foreach
.你必须在你的上下文中加入一些可迭代的东西.例如,使bar
这是一个数组或Collection
某种类型:
#foreach ($foo in $bar)
$foo
#end
Run Code Online (Sandbox Code Playgroud)
或者,如果您想迭代一个数字范围:
#foreach ($number in [1..34])
$number
#end
Run Code Online (Sandbox Code Playgroud)
小智 6
当我尝试循环列表时,我找到了解决方案。将列表放在另一个类中,并为列表obj创建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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后对于速度上下文,将Extraclass作为输入。例如。
ExtraClass e = new ExtraClass(your list);
VelocityContext context = new VelocityContext();
Run Code Online (Sandbox Code Playgroud)
context.put(“ data”,e); 在模板内
#foreach ($x in $data.userList)
$x.fieldname //here $x is the actual obj inside the list
#end
Run Code Online (Sandbox Code Playgroud)