如何在速度模板中使用’for’循环?

我只是用google搜索’for loop’,但看起来速度只有’foreach’。

如何在力度模板中使用“for loop”?

只有#foreach 。 你必须在你的上下文中加入一些可迭代的东西。 例如,make bar是一个数组或某种Collection

 #foreach ($foo in $bar) $foo #end 

或者,如果您想迭代一个数字范围:

 #foreach ($number in [1..34]) $number #end 

想要在foreach循环中添加迭代信息,可以从特殊的$foreach属性访问:

 #foreach ($foo in $bar) count: $foreach.count index: $foreach.index first: $foreach.first last: $foreach.last #end 

(上次我检查的last包含了一个bug)

当我试图循环列表时,我找到了解决方案。 将列表放在另一个类中,并为列表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; } } 

然后对于速度上下文,将Extraclass作为输入。 例如。

  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