How to loop all variables in VelocityContext?

我与影子孤独终老i 提交于 2021-01-27 05:25:22

问题


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);

回答1:


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



回答2:


how can I loop through all the variables or attributes present in VelocityContext ?

If I didn't misunderstood you, do you want to know how to loop through the key/value pairs contained in the map that you constructed your object with ?

If yes, you could call the method internalGetKeys() which will return the array of keys contained in the VelocityContext object.

Then loop through all the keys and use internalGet() to get the value associated with each key.

It would be something like this :

        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);
        }


来源:https://stackoverflow.com/questions/16982791/how-to-loop-all-variables-in-velocitycontext

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!