Alex Rivera | Logout

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

Asked 2008-10-10T15:22:55.063
25

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?

Edit
Report

3 Answers

27

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]).

answered 2009-02-02T22:58:32.357
1

Brian's answer is indeed correct, although you might like to know that upcoming Velocity 1.6 has direct support for arrays; see the Velocity documentation for more information.

answered 2008-10-13T19:34:38.300
0

I ended up using the ListTool from the velocity-tools.jar. It has methods to access an array's elements and also get its size.

answered 2009-05-13T06:01:06.407

Your Answer