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

Som*_*omu 5 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);
Run Code Online (Sandbox Code Playgroud)

Ser*_*riu 5

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

爪哇:

attributes.put("vcontext", attributes);
Run Code Online (Sandbox Code Playgroud)

.vm:

#foreach ($entry in $vcontext.entrySet())
  $entry.key => $entry.value
#end
Run Code Online (Sandbox Code Playgroud)

由于您在读取实时上下文的同时还执行修改地图的代码,因此您将获得异常。所以最好先制作地图的副本:

#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
Run Code Online (Sandbox Code Playgroud)