java 在 Velocity 中取消设置变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/657548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unsetting a variable in Velocity
提问by Simon Nickerson
Is it possible to set a Velocity reference to 'null' or 'undefined'?
是否可以将 Velocity 引用设置为“null”或“undefined”?
The Velocity template language referencesays
#set- Establishes the value of a reference Format:
# [ { ] set [ } ] ( $ref = [ ", ' ]arg[ ", ' ] )Usage:
$ref- The LHS of the assignment must be a variable reference or a property reference.
arg- The RHS of the assignment, arg is parsed if enclosed in double quotes, and not parsed if enclosed in single quotes. If the RHS evaluates to null, it is not assigned to the LHS.(emphasis mine)
#set- 建立参考格式的值:
# [ { ] set [ } ] ( $ref = [ ", ' ]arg[ ", ' ] )用法:
$ref- 赋值的 LHS 必须是变量引用或属性引用。
arg- 赋值的 RHS, arg 如果用双引号括起来,则解析,如果括在单引号中,则不解析。如果 RHS 评估为空,则不会将其分配给 LHS。(强调我的)
I cannot find an equivalent #unsetmacro.
我找不到等效的#unset宏。
采纳答案by vartec
Read on...
继续阅读...
Depending on how Velocity is configured, it is usually not possible to remove an existing reference from the context via this mechanism. (Note that this can be permitted by changing one of the Velocity configuration properties)
根据 Velocity 的配置方式,通常无法通过此机制从上下文中删除现有引用。(请注意,这可以通过更改 Velocity 配置属性之一来允许)
In the VE default configuration has property
在 VE 默认配置中有属性
directive.set.null.allowed = false
if true, having a right hand side of a #set() statement with an invalid reference or null value will set the left hand side to null. If false, the left hand side will stay the same
如果为真,#set() 语句的右侧带有无效引用或空值会将左侧设置为空。如果为假,左侧将保持不变
Change it to trueusing setProperty()on org.apache.velocity.app.Velocityand you're ready to go.
将其更改为true使用setProperty()上org.apache.velocity.app.Velocity,你准备好去。
回答by
You can set the reference to false. As a non null reference is considered true, you can then test if the reference is set. This is useful in loops.
您可以将引用设置为 false。由于认为非空引用为真,您可以测试是否设置了引用。这在循环中很有用。
#foreach ($obj in $list) #set ($x = false) #set ($x = $obj.maybeNull()) #if ($x) ... $x #end #end
回答by Thilo
If you are trying to get scoped variables, you can abuse the scope established by #foreach:
如果您试图获取作用域变量,您可以滥用由#foreach以下方法建立的作用域:
#foreach($localVar in [ 'theValue'])
#end
## localVar will be unset (or returned to previous value) again

