'Java velocity vm file #set use boolean variable
We can not use Boolean variable by #set
when I find velocity project guidelines in Apache official site, but it is also worked when I use in my project.
#set($isRight=true)
#if($isRight)
##execute
#end
#set($isRight=false)
#if($isRight)
##not execute
#end
I want to know whether #set
Boolean variable is supported by velocity and the way I use whether is legal.
Solution 1:[1]
Experience shows that your example works, but you are right that the documentation does not say explicitly that you can assign a Boolean value to variables using the #set
directive (there are meticulously detailed cases and lack of information about Boolean among them).
Therefore, if you want to be sure that you are writing code 100% compatible with the documentation, then instead of explicit Boolean you can use other values, which according to the documentation will be converted to Boolean. They are e.g. 0
for false
and 1
for true
.
Then your example would look like this:
#set ($isRight = 1)
#if ($isRight)
## execute
#end
#set ($isRight = 0)
#if ($isRight)
## not execute
#end
Solution 2:[2]
In velocity, there are no explicit data types and hence there is no Boolean variables support. But since velocity has been built on JAVA platform, if you specify a compatible value then it can give you expected results in such operations like the "if" operation (the one shown in your code). This is because in Java, a boolean value is expected in an if expression and you are providing something which can be easily casted to a boolean.
If you give something like #set($isRight=true1) , the above written code will be internally treated by the Java engine like you specified a String inside 'if' expression which couldn't be casted to a boolean and hence will throw up a type cast exception(or ClassCastException). This will happen with any value other than 'true' or 'false' which are actually strings here but can be successfully casted to Boolean which is expected inside 'if' expression.
Thus its not the Boolean type support, but the Java implementation behind the scenes makes the things work.
Solution 3:[3]
Velocity 2.0, yet to be released, does support such tests.
Meanwhile, you can resort to #if("isRight"=="true")...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | Claude Brisson |