Search code examples
javaapachevelocity

How can I #evaluate a Velocity Variable within a logic statement?


I am using Apache Velocity templates.

In the following I loop from 1..n and expect $myVar to be equal to a concatenation of the value of $originalVar and '_n' (where n is a number from 1..n) e.g. 'test_1' where 'test' is the value of $originalVar and 1 is the value of n.

This can be achieved as follows :

#foreach($i in [1 .. $num_of_iterations])
    #set($myVar= "$originalVar_$i")
    #evaluate($myVar)
#end

However, I am unable to #evaluate within a logic statement as per below:

#if (#evaluate($myVar)  == "false")
    ...
#end

Therefore, how can I #evaluate a variable within a logic statement?


Solution

  • Just enclose the #evaluate into quotes:

    #foreach($i in [1 .. $num_of_iterations])
        #set($myVar= "$originalVar_$i")
        #if("#evaluate($myVar)" == "true")
          found true
        #else
          found false
        #end
    #end