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

2

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
  • 4,085
  • 1
  • 22
  • 30
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

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
0

You can use get():

#set( $temp = $data.get($key) )
robo
  • 369
  • 3
  • 6