Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

construct variable names dynamically in velocity

Tags:

velocity

I would like to know if it is possible to construct name of variable into velocity dynamically.

i.e. lets say I've 6 variables into velocity template [name1, name2, name3 .. name6] I would like to output them. So I'm looking in something like:

#foreach ( $counter in [1..6] )
${name${counter}}
#end

is it possible somehow?

like image 890
Dmytro Pastovenskyi Avatar asked Jun 13 '13 10:06

Dmytro Pastovenskyi


2 Answers

It is possible using the #evaluate directive:

#evaluate ('$name1')

#set ($d = '$')
#foreach ($i in [1..6])
  #set ($varName = "${d}name${i}")
  #evaluate($varName)
#end
like image 121
Sergiu Dumitriu Avatar answered Sep 24 '22 15:09

Sergiu Dumitriu


You could construct a map and build the names of the keys to retrieve the values you want:

#set( $map = {"${name}1":'value1', "${name}2":'value2'} )

#foreach ( $counter in [1..6] )
    #set( $key = "${name}$counter" )
    $map.get(${key})
#end
like image 40
Edd Avatar answered Sep 21 '22 15:09

Edd