construct variable names dynamically in velocity

▼魔方 西西 提交于 2019-11-27 23:10:28
Sergiu Dumitriu

It is possible using the #evaluate directive:

#evaluate ('$name1')

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

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

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