32

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

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

Moon
  • 22,195
  • 68
  • 188
  • 269

3 Answers3

44

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)

serg
  • 109,619
  • 77
  • 317
  • 330
  • Exactly what I needed. I needed to write the index in my template. Thanks for this post! – Karthic Raghupathi May 26 '13 at 03:56
  • 2
    If you're stuck with Velocity 1.6 (f.e. as used by Confluence), only `$velocityCount` and `$velocityHasNext` are available (http://velocity.apache.org/engine/releases/velocity-1.6/user-guide.html#Loops) – sendmoreinfo Jun 17 '14 at 07:21
  • 1
    You can also get at these variables from within nested loops with `$foreach.parent.whatever` e.g. `$foreach.parent.parent.index` gets the index of the outer loop from within a triply nested foreach loop. – starwarswii Jul 25 '17 at 14:23
42

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
WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
8

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
Sarbe97
  • 91
  • 2
  • 5