gpt4 book ai didi

java - 如何循环 VelocityContext 中的所有变量?

转载 作者:搜寻专家 更新时间:2023-10-31 19:56:08 24 4
gpt4 key购买 nike

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

.虚拟机:

#foreach ($entry in $vcontext.entrySet())
$entry.key => $entry.value
#end

由于您在读取实时上下文的同时还执行修改 map 的代码,因此您会遇到异常。所以最好先复制 map :

#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

关于java - 如何循环 VelocityContext 中的所有变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16982791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com