Thursday, January 15, 2015

How to display null as empty string with Apache Velocity

We used the following Syntax to display attribute's value in Apache Velocity.
$myValue


But the problem is that, we the value carried by the attribute is null.
Velocity is not displaying an empty string or "null",
it display the attribute name that is being used.

attribute: [ $myValue1, $myValue2, $myValue3, $myValue4 ]
value:      [ "First", null, "Third", "" ]
Output:   [ First, $myValue2, Third,  ]


To display the NULL value as an empty string. we just need to add "!" after "$"

attribute: [ $!myValue1, $!myValue2, $!myValue3, $!myValue4 ]
value:      [ "First", null, "Third", "" ]
Output:   [ First, , Third,  ]


Done!!

Tuesday, January 13, 2015

How to retrieve value in map with Apache Velocity

Assuming we have a HashMap with the following value

HashMap myMap = new HashMap();
myMap.put("k1", "v1");
myMap.put("k2", "v2");
myMap.put("k3", "v3");


put the HashMap into the VelocityContext.

VelocityContext context = new VelocityContext();
context.put("myMap", myMap);


To retrieve the map value in the Velocity template (.vm file),
Use the following syntax to retrieve map value with constant key.

$myMap.get("k1");
$myMap.get("k2");
$myMap.get("k3");


Use the following syntax to retrieve map value with dynamic key.

$myMap.get($mapKey1);
$myMap.get($mapKey2);
$myMap.get($mapKey3);


Done!!

LinkWithin

Related Posts Plugin for WordPress, Blogger...