pomegranate
pomegranate

Reputation: 765

Velocity: Dereferencing a variable with a concatinated name

I'm new to Velocity and couldn't find something that addressed this problem, so I apologize if it's trivial. Say I have the following 200 variables.

  #set( $a1 = "apple", $b1 = "red", $a2 = "banana", $b2 = "yellow" .... 
       .... $a100 = "plum", $b100 = "purple)

I want to output the fruit followed by its color. Is there a way to concatenate "a" and "b" with each of the numbers in the range(1,100) and then dereference the variable? Something like

 #foreach( $i in [1..100])
     #set( $fruit = "a{$i}")
     #set( $color = "b{$i}")

     The fruit $fruit is the color $color. 

 #end

I've tried many things, but can ever only manage to output $a1 $b1 as strings rather than what they refer to. Thanks!

Upvotes: 1

Views: 217

Answers (1)

Sergiu Dumitriu
Sergiu Dumitriu

Reputation: 11601

#set ($d = '$')
#set ($h = '#')
#foreach ($i in [1..100])
  #evaluate("${h}set(${d}fruit = ${d}a${i})")
  #evaluate("${h}set(${d}color = ${d}b${i})")
  The fruit ${fruit} is the color ${color}.
#end

Upvotes: 4

Related Questions