8

I am using Velocity Templating Language and currently have:

#set ( $stringList = $string.split(",") )

which works fine and splits the string up using a ',' as a delimiter as expected.

My question is how do i now access each of the elements in the $stringList?

I have tried:

$stringList.get(0)
$stringList[0]
$stringList.[0]
${stringList}.get(0)

I am using Velocity in JIRA and JIRA happens to use Velocity version 1.4 which apparently doesn't have support for accessing arrays as tried above.

Any help is much appreciated.

Mr-DC
  • 799
  • 5
  • 14
  • 25

4 Answers4

5

Tested in Velocity 1.6.

#foreach ($element in $string.split(";"))
   $element
#end
oomkoos
  • 173
  • 2
  • 7
2

It works when I convert the array to a List using Arrays.asList() and then use methods from List to access elements.

I add the following to the context:

context.put("arrays", Arrays.class);

In velocity template I use:

#set ( $array = $getarray.getArray() )

$arrays.asList($array).get(0)

With a String-Array as follows

new String[] {"test1", "test2", "test3", "test4"};

I get the expected output:

test1
centic
  • 15,565
  • 9
  • 68
  • 125
  • Thanks for the suggestion centic but it doesnt seem to work. Thanks anyway. – Mr-DC Jan 08 '12 at 21:49
  • I tried it now and it worked with the steps listed above, can you post you current code so we can see why it does not work for you? – centic Jan 10 '12 at 11:44
1

As of Velocity 1.6, all array references are now "magically" treated as if they are fixed-length lists. This means that you can call java.util.List methods on array references. So, if you have a reference to an array (let's say this one is a String[] with three values), you can do:

$myarray.isEmpty()

$myarray.size()

$myarray.get(2) 

$myarray.set(1, 'test')

Source: http://velocity.apache.org/engine/releases/velocity-1.7/user-guide.html#methods

Community
  • 1
  • 1
juan
  • 1,917
  • 2
  • 16
  • 14
0

Its also possible to push elements into an array like this.

#set ($matchingProducts = [])
#set($bar = $matchingProducts.add($p))
j0k
  • 22,600
  • 28
  • 79
  • 90