速度模板引擎:如何检查变量是否通过传递的参数在宏中设置



我目前确实有一个工作方法,用于检查是否设置了变量。我喜欢这个

CHECKING EACH VARIABLE:
#if($!{vh})
vh instance found!<br>
Classname: ${vh.class.name}<br>
#end
#if($!{su})
su instance found!<br>
Classname: ${su.class.name}<br>
#end

这将当前打印此:

检查每个变量:找到vh实例!类名:de.integration.commons.VelocityXPathHelper

找到su实例!类名:de.integration.commons.StringUtils

提示:我之前将这些变量注入到上下文中。

由于我确实需要检查很多变量,而注入的变量有时会有所不同,所以我创建了一个宏,该宏应该也这样做,并在一个字符串数组上组合一个循环,该数组包含已知的注入变量,如下所示:

#* Macro - checkIfVariableExists
This macro checks if variable exists with the quit reference notation
check http://velocity.apache.org/engine/devel/user-guide.html#quiet-reference-notation for more information *#
#macro (checkIfVariableExists $variablename)
#if($!{variablename})
$variablename instanz found!<br>
Classname: ${variablename.class.name}<br>
#end
#end
RESULT FROM LOOP:
#set( $toCheck = ["vh","su","anothervariable","...","....", "....."] )
#foreach( $value in $toCheck )
#checkIfVariableExists($value)
#end

然而,这将不起作用,并导致此输出:

循环结果:找到vh instanz!类名:java.lang.Stringsu instanz找到了!类名:java.lang.String

如何实现此功能?我确实知道value是一个String,但是我想像使用第一种方法一样使用它的值。有什么想法吗?Im使用速度引擎1.7,并且Im无法更改到更高版本。

如果您正在检查上下文中可用的内容,您也可以使用Velocity上下文工具(https://velocity.apache.org/tools/3.0/apidocs/org/apache/velocity/tools/generic/ContextTool.html)。

它从VelocityTools 2.0版本开始可用(这与Velocity版本不对应!(,您可以使用

$context.keys

以查找上下文中可用的所有变量。(这是一个Set,所以方法contains可以工作。(

最新更新