如何在VelocityContext中循环所有变量?

时间:2013-06-07 11:15:50

标签: java velocity

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

2 个答案:

答案 0 :(得分:4)

默认情况下,您无法执行此操作,因为您无法获取上下文对象。但是你可以将上下文本身放在上下文中。

爪哇:

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

答案 1 :(得分: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);
        }
相关问题