Create and iterate through an array in Velocity Template Language

vtl
75,479

Solution 1

According to Apache Velocity User Guide, right hand side of assignments can be of type

  • Variable reference
  • List item
  • String literal
  • Property reference
  • Method reference
  • Number literal
  • ArrayList
  • Map

You can create an empty list, which would satisfy all your needs for an array, in an Apache Velocity template with an expression like:

#set($foo = [])

or initialize values:

#set($foo = [42, "a string", 21, $myVar])

then, add elements using the Java add method:

$foo.add(53);
$foo.add("another string");

but beware, as the Java .add() method for the list type returns a boolean value, when you add an element to the list, Velocity will print, for instance, "true" or "false" based on the result of the "add" function.

A simple work around is assigning the result of the add function to a variable:

#set($bar = $foo.add(42))

You can access the elements of the list using index numbers:

<span>$foo[1]</span>

Expression above would show a span with the text "a string". However the safest way to access elements of a list is using foreach loops.

Solution 2

Creating an array is easy:

#set($array = [])

Putting an element into an array is also easy:

$array.add(23)

Getting an element from an array depends from your Velocity version. In Velocity 1.6 you must use

$array.get($index)

Since Velocity 1.7 you can use the classic form:

$array[$index]

Solution 3

I haven't created an array in VTL but passed arrays to VTL context and used them. In VTL, you can not retrieve array contents by index, you only use foreach, as example this code is copied from my Dynamic SQL generation VTL Script:

#foreach( $col in $Columns ) SUM($col.DBColumn) AS ''$col.Name''#if($velocityCount!=$Columns.Count),   #end  #end 

For this reason, we also can not have 2D arrays. When I needed an array to store 2 objects in a row, I used the workaround of defining a new class, and putting objects of that class in the single dimensional array.

Share:
75,479
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    How to create an array in VTL and add contents to the array? Also how to retrieve the contents of the array by index?

  • sproketboy
    sproketboy about 9 years
    Note though that $foo.add(53); renders 'true' or 'false' in the document. To prevent that you'd need to wrap it in an #if.
  • Irmak Cakmak
    Irmak Cakmak about 9 years
    Case for rendering true or false was already covered in the answer.
  • sproketboy
    sproketboy about 9 years
    Oh yeah sorry. I just realized. You can use the add method with the index parameter which returns void.