Friday, October 29, 2010

Why do I see output when I call put() on a HashMap in Velocity?

Consider the following Velocity code:
#set($myMap = $contents.getEmptyMap())
$myMap.put("first", "first value")
$myMap.put("second", "second value")
$myMap.put("third", "third value")

<p>$myMap.first</p>
<p>$myMap.second</p>
<p>$myMap.third</p>
The output of that is as below.

$myMap.put("first", "first value") $myMap.put("second", "second value") $myMap.put("third", "third value")

first value

second value

third value
The problem is that put() returns something (it's return type is not void) and Velocity is trying to evaluate it somehow. The fix is easy enough though. Use a dummy variable to catch the return value.

#set($myMap = $contents.getEmptyMap())
#set($dontOutput = $myMap.put("first", "first value"))
#set($dontOutput = $myMap.put("second", "second value"))
#set($dontOutput = $myMap.put("third", "third value"))