How to use 'for' loop in velocity template?

53,144

Solution 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

Solution 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)

Solution 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
Share:
53,144
Moon
Author by

Moon

Updated on December 21, 2020

Comments

  • Moon
    Moon over 3 years

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

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