construct variable names dynamically in velocity

ぃ、小莉子 提交于 2019-11-26 21:38:32

问题


I would like to know if it is possible to construct name of variable into velocity dynamically.

i.e. lets say I've 6 variables into velocity template [name1, name2, name3 .. name6] I would like to output them. So I'm looking in something like:

#foreach ( $counter in [1..6] )
${name${counter}}
#end

is it possible somehow?


回答1:


It is possible using the #evaluate directive:

#evaluate ('$name1')

#set ($d = '$')
#foreach ($i in [1..6])
  #set ($varName = "${d}name${i}")
  #evaluate($varName)
#end



回答2:


You could construct a map and build the names of the keys to retrieve the values you want:

#set( $map = {"${name}1":'value1', "${name}2":'value2'} )

#foreach ( $counter in [1..6] )
    #set( $key = "${name}$counter" )
    $map.get(${key})
#end



回答3:


Here is a trick to set velocity variable with dynamic name.

If you manage to tune velocity context beforehand in java code like this:

VelocityContext context = new VelocityContext(paramsMap);
context.put("all", paramsMap);

then it would be possible to define dynamic vars in template like this:

#set($dynamicDef = "varName=varValue")
#set($dynamicName = $dynamicDef.substring(0, $dynamicDef.indexOf('=')))
#set($dynamicValue = $dynamicDef.substring($dynamicDef.indexOf('=')).substring(1))
## create var with dynamic name
$all.put($dynamicName, $dynamicValue)

and use them later like this:

#if ($varName)
varName=$varName ## prints varName=varValue
#end


来源:https://stackoverflow.com/questions/17084542/construct-variable-names-dynamically-in-velocity

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