在我的 Velocity 模板(.vm 文件)中,如何循环遍历中存在的所有变量或属性VelocityContext
?参考下面的代码,我希望模板能够写入上下文中传递的所有水果的名称和数量。
Map<String, Object> attribues = ...;
attribues.put("apple", "5");
attribues.put("banana", "2");
attribues.put("orange", "3");
VelocityContext velocityContext = new VelocityContext(attribues);
velocityEngine.mergeTemplate(templateLocation, encoding, velocityContext, writer);
默认情况下你不能这样做,因为你无法获取上下文对象。但你可以把上下文本身放在上下文中。
Java:
attributes.put("vcontext", attributes);
.vm:
#foreach ($entry in $vcontext.entrySet())
$entry.key => $entry.value
#end
由于您在读取实时上下文的同时还执行修改映射的代码,因此您将遇到异常。所以最好先复制一份地图:
#set ($vcontextCopy = {})
$!vcontextCopy.putAll($vcontext)
#foreach ($entry in $vcontextCopy.entrySet())
## Prevent infinite recursion, don't print the whole context again
#if ($entry.key != 'vcontext' && $entry.key != 'vcontextCopy')
$entry.key => $entry.value
#end
#end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)