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

34

我刚刚在谷歌上搜索了“for循环”,但是看起来Velocity模板引擎只有“foreach”。

我该如何在Velocity模板中使用“for循环”?


1
最佳答案在下面,由@serg提供:https://dev59.com/cW025IYBdhLWcg3w_bCr#5683891 - redben
3个回答

44

只有 #foreach。你需要在上下文中放置可迭代的东西。例如,使得一个名为bar的数组或者Collection可用:

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

或者如果你想遍历一个数字范围:

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

// 谢谢!我不明白为什么他们没有最基本的循环! - Moon
6
foreach 是最基本的循环类型,for 则是更高级的循环类型。 - Nathan Bubna
请注意,Velocity 中的范围是包含的,因此第二个示例将循环34次,其中 $number 的值从1到34。 - Starwarswii

44

想补充一点,在foreach循环内可以通过特殊的$foreach属性来访问迭代信息:

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

(上次我检查时,last还存在一个错误)


正是我所需要的。我需要在我的模板中编写索引。感谢您的帖子! - Karthic Raghupathi
2
如果你被困在Velocity 1.6中(例如Confluence使用的版本),只有$velocityCount$velocityHasNext是可用的(http://velocity.apache.org/engine/releases/velocity-1.6/user-guide.html#Loops)。 - sendmoreinfo
1
你也可以在嵌套循环中使用 $foreach.parent.whatever 访问这些变量,例如 $foreach.parent.parent.index 可以在三重嵌套的 foreach 循环中获取外部循环的索引。 - Starwarswii

8

在尝试循环列表时,我找到了解决方案。 将列表放入另一个类中,并为列表对象创建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

这适用于地图吗? - JP. K.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接