Velocity: Is a any way to check if variable is defined

北城以北 提交于 2021-01-21 06:15:42

问题


I want to include one template nested into others 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?


回答1:


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.




回答2:


#if($hideMyControl)
    // your code
#end

If $hideMyControl is defined, your code will execute




回答3:


#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.




回答4:


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!




回答5:


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



回答6:


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.



来源:https://stackoverflow.com/questions/4825636/velocity-is-a-any-way-to-check-if-variable-is-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!