Velocity: Is a any way to check if variable is defined
I want to include one template nested
into others开发者_如何学Python cont1
, cont2
, cont3
.
And nested template should be hide one specific control for cont1 only.
Before inclusion into cont1
I would like to assign value to some flag variable $hideMyControl
.
And inside nested template I would like to check if $hideMyControl
is assigned value.
How to perform such check?
#if($hideMyControl)
// your code
#end
If $hideMyControl
is defined, your code will execute
You can do this using
#if($!{$articleLeader})
// Perform your operation or the template part you want to show.
#end
For more info, see the 'formal reference' section of the Apache Velocity Reference Manual.
#if($!{hideMyControl} != "")
## do something if $hideMyControl is defined
#end
This works for me in AWS API Gateway Body Mapping Templates. Please refer to Quiet Reference Notation in Velocity User Guide for more information.
I was using
#if ($hideMyControl)
//do something
#end
since a few months ago, however today its not working anymore.
I came here to find help, and noticed a new way of writing it :
#if($!{$hideMyControl})
// do something
#end
this code works!
According to the docs for Strict Reference Mode it is possible to several constructions to check if variable is defined.
#if ($foo)#end ## False #if ( ! $foo)#end ## True #if ($foo && $foo.bar)#end ## False and $foo.bar will not be evaluated #if ($foo && $foo == "bar")#end ## False and $foo == "bar" wil not be evaluated #if ($foo1 || $foo2)#end ## False $foo1 and $foo2 are not defined
So this code works in my case.
#if( !$value )
// Perform your operation or the template part you want to show.
#end
To check if $hideMyControl is in Velocity context and IS NOT boolean 'true' value (or 'false' as well):
#if ($hideMyControl && $hideMyControl != true)
##do stuff
#end
Sure, if you really use your $hideMyControl variable as boolean type, you don't need second part of condition.
精彩评论