5

在我的 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);
4

2 回答 2

5

默认情况下,您不能这样做,因为您无法获取上下文对象。但是您可以将上下文本身放在上下文中。

爪哇:

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
于 2013-06-08T01:23:34.630 回答
2

如何循环遍历中存在的所有变量或属性 VelocityContext

如果我没有误解你,你想知道如何遍历你构建对象的映射中包含的键/值对吗?

如果是,您可以调用internalGetKeys()将返回VelocityContext对象中包含的键数组的方法。

然后循环遍历所有键并使用internalGet()来获取与每个键关联的值。

它会是这样的:

        VelocityContext velocityContext = new VelocityContext(attribues);
        Object[] keys = velocityContext.internalGetKeys();

        for(Object o : keys){
            String key = (String)o;
            String value = (String)velocityContext.internalGet(key);
            System.out.println(key+" "+value);
        }
于 2013-06-07T11:21:18.557 回答