我正在尝试通过功能动态传递名称来更新不同的地图。有可能实现吗?因为我在下面的代码中遇到了一些问题。但我引用了此链接construct variable names dynamically in velocity 它说我们可以动态地建立变量名。所以我问一些放置操作对于该动态创建的地图也是可行的。有办法吗?
.vm
#set($sampleArray = [])
#set($Map1 = {})
#set($Map2 = {})
#sampleTest( 'adsdasd' 'q1' 'Map1')
#sampleTest( 'dsadsad' 'ans1' 'Map1')
#sampleTest('fgbfd' 'q2' 'Map1')
#sampleTest( 'fdmieS' 'ans2' 'Map1')
#sampleTest('hhhfs' 'q4' 'Map2')
#sampleTest( 'sdfq' 'ans4' 'Map2')
#macro( sampleTest $Str1 $expectedString $MapStr)
#set ($d = '$')
#set ($varName = "${d}$MapStr") -- setting dynamic name of map
$varName.put($expectedString, $Str1)
#if ($varName.size()%2 == 0 )
$sampleArray.add($varName) -- adding maps to array after every size of map is 2
#set($varName = {}) -- emptying map after map size is 2
#end
#end
$sampleArray
$Map1
$Map2
实际输出
[]
{}
{}
预期产量
[{q1=adsdasd, ans1=dsadsad},{q2=fgbfd, ans2=fdmieS},{q4=hhhfs, ans4=sdfq}]
{q2=fgbfd, ans2=fdmieS}
{q4=hhhfs, ans4=sdfq}