What is the best way to access an array inside Velocity?

Sergio del Amo picture Sergio del Amo · Oct 10, 2008 · Viewed 60.5k times · Source

I have a Java array such as:

String[] arr = new String[] {"123","doc","projectReport.doc"};

In my opinion the natural way to access would be:

 #set($att_id = $arr[0])
 #set($att_type = $arr[1])
 #set($att_name = $arr[2])

But that it is not working. I have come with this workaround. But it a bit too much code for such an easy task.

#set($counter = 0)
#foreach($el in $arr)
    #if($counter==0)
        #set($att_id = $el)
    #elseif($counter==1)
        #set($att_type = $el)
    #elseif($counter==2)
         #set($att_name = $el)
    #end
    #set($counter = $counter + 1)
#end

Is there any other way?

Answer

Nathan Bubna picture Nathan Bubna · Feb 2, 2009

You can use use Velocity 1.6: for an array named $array one can simply do $array.get($index).

In the upcoming Velocity 1.7, one will be able to do $array[$index] (as well as $list[$index] and $map[$key]).