How to use 'for' loop in velocity template?

柔情痞子 提交于 2019-12-18 12:10:47

问题


I just googled for 'for loop', but it looks like velocity has 'foreach' only.

How do I use 'for loop' in velocity template?


回答1:


There's only #foreach. You'll have to put something iterable on your context. E.g. make bar available that's an array or Collection of some sort:

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

Or if you want to iterate over a number range:

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



回答2:


Wanted to add that iteration information inside foreach loop can be accessed from special $foreach property:

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

(last time I checked last contained a bug though)




回答3:


I found the solution when i was trying to loop a list. Put the list in another class and create getter and setter for the list obj. e.g

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;
    }

}

Then for velocity context put the Extraclass as the input. eg.

  ExtraClass e = new ExtraClass(your list);
VelocityContext context = new VelocityContext();

context.put("data", e); Within template

#foreach ($x in $data.userList)
        $x.fieldname    //here $x is the actual obj inside the list
    #end


来源:https://stackoverflow.com/questions/5683690/how-to-use-for-loop-in-velocity-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!