in velocity can you iterate through a java hashmap's entry set()?

Ayrad picture Ayrad · Jan 12, 2010 · Viewed 47.6k times · Source

Can you do something like this in a velocity template?

#set ($map = $myobject.getMap() )
#foreach ($mapEntry in $map.entrySet())
    <name>$mapEntry.key()</name>
    <value>$mapEntry.value()</value>
#end

it outputs blank tags like so:

<name></name> 

and

<value></value> 

What am I doing wrong?

Answer

Yoni picture Yoni · Jan 12, 2010

Your mistake is referring to key and value as methods (with trailing "()" parenthesis) instead of as properties. Try this:

#set ($map = $myobject.getMap() )
#foreach ($mapEntry in $map.entrySet())
    <name>$mapEntry.key</name>
    <value>$mapEntry.value</value>
#end

In other words, use either a property, like mapEntry.key, or the method, like mapEntry.getKey().