42

I am using velocity for email templates in my java/spring 3 app.
How could I get the size of an ArrayList added to the model from within the template.

Apache
  • 1,060
  • 5
  • 21
  • 38
Danny
  • 1,291
  • 4
  • 13
  • 16

3 Answers3

52

I've never used Velocity, but its VTL reference guide says that calling a method is done using $customer.getAddress() or ${purchase.getTotal()}. So I would use ${myArrayList.size()}.

starwarswii
  • 2,187
  • 1
  • 16
  • 19
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 7
    The reference is one of the funniest pieces of example code I have seen in a while. Had to clean coffee from my screen... – Namphibian Mar 09 '15 at 20:45
23

A collection can be accessed like any other object, so $collection.size() will contain a value.

Arrays are special cased to behave like List, so though $array.length doesn't work, $array.size() works.

In older versions of Velocity (pre 1.6) you'd use ListTool and ArrayTool.

starwarswii
  • 2,187
  • 1
  • 16
  • 19
dimo414
  • 47,227
  • 18
  • 148
  • 244
0

Quote from the developer guide:

Object [] Regular object array, not much needs to be said here. Velocity will internally wrap your array in a class that provides an Iterator interface, but that shouldn't concern you as the programmer, or the template author. Of more interest, is the fact that Velocity will now allow template authors to treat arrays as fixed-length lists (as of Velocity 1.6). This means they may call methods like size(), isEmpty() and get(int) on both arrays and standard java.util.List instances without concerning themselves about the difference.

So using size() works equally well on java.util.List and java arrays.

starwarswii
  • 2,187
  • 1
  • 16
  • 19
cristi
  • 161
  • 1
  • 2
  • 7