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);
Developer file used by Velocity, a Java-based template engine; written using the Velocity Template Language (VTL); contains VTL statements inserted in a normal text document; often used for auto-generating Web source code and class skeletons.
Approach 1: The obvious approach: Run and check. Run Velocity against the template to be checked. Look at the output and see if it is what you desired. This must be the most primitive testing approach, but most people nowadays are too lazy and want this done by the computer.
You would typically do something like #set ($oldIndex = $number. toNumber($oldIndex)) if you have the NumberTool present in your context, for instance. And that's it, $oldIndex contains an integer! Please note that the Integer.
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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With