Somu
Somu

Reputation: 3750

How to loop all variables in VelocityContext?

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

Upvotes: 5

Views: 6314

Answers (2)

Sergiu Dumitriu
Sergiu Dumitriu

Reputation: 11601

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

Upvotes: 5

Alexis C.
Alexis C.

Reputation: 93842

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

Upvotes: 2

Related Questions