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

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)

  • 如果你坚持使用Velocity 1.6(Confluence使用的fe),只有`$ velocityCount`和`$ velocityHasNext`可用(http://velocity.apache.org/engine/releases/velocity-1.6/user-guide的.html#循环) (2认同)

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)

  • foreach是最基本的循环.因为是先进的. (4认同)

小智 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)