如何循环 VelocityContext 中的所有变量? [英] How to loop all variables in VelocityContext?
问题描述
在我的 Velocity 模板(.vm 文件)中,如何遍历 VelocityContext
中存在的所有变量或属性?参考以下代码,我希望模板写入上下文中传递的所有水果的名称和数量.
In my Velocity template (.vm file) how can I loop through all the variables or attributes present in VelocityContext
? In reference to the below code, I would like the template to write the names and count of all the fruits passed in context.
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);
推荐答案
默认情况下您不能这样做,因为您无法获得上下文对象.但是你可以把上下文本身放在上下文中.
By default you can't do that, since you can't get hold of the context object. But you can put the context itself in the context.
Java:
attributes.put("vcontext", attributes);
.vm:
#foreach ($entry in $vcontext.entrySet())
$entry.key => $entry.value
#end
由于您在读取实时上下文的同时还执行修改地图的代码,因此您将遇到异常.所以最好先把地图复制一份:
Since you're reading the live context while also executing code that modifies the map, you're going to get exceptions. So it's best to make a copy of the map first:
#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
这篇关于如何循环 VelocityContext 中的所有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!