I just googled for 'for loop', but it looks like velocity has 'foreach' only.
How do I use 'for loop' in velocity template?
I just googled for 'for loop', but it looks like velocity has 'foreach' only.
How do I use 'for loop' in velocity template?
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
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)
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