4

I'm facing a difficult problem when I am coding with Velocity Template.

#set($key = "")

$key is a dynamic variable.

So when I want to get the property of another variable which has property is $key. What will I do?

#set($temp = #evaluate("$data.$key");

or

#set($temp = $data.$key);

All of them is not valid. Please help me!!!

3 Answers3

1

Since the passed string is evaluated in two steps, you need to escape the first dollar (with a backslash) and the quotes (by doubling them) at the first step. You would do:

#set($temp = "#evaluate(""\$data.$key"")")
Claude Brisson
  • 3,680
  • 1
  • 24
  • 27
0

To access other velocity variable's property you just need to address it as $variableName.propertyName. see velocity properties. in your case:

#set($temp = $data.key);

I don't know of such built-in reflection capabilities, even ClassTool of velocity tools support reflection but not allowing executing:

It was not designed with reflective execution of code in mind and thus provides no facilities for code execution, nor direct access to the actual methods

user7294900
  • 52,490
  • 20
  • 92
  • 189
0

You can use get():

#set( $temp = $data.get($key) )
robo
  • 329
  • 2
  • 6