Apache velocity directives and how to use them
1. IF
Start if with #if and end the statement with #end you can use #else which is optional
In Java to set parameter use:
2. Iterating Through List (FOREACH):
In java use following code:
3. Iterating through Map
In java use:
4. Iterating through array(FOREACH)
5. Computing in VTL (SET):
6. Converting a template to string
1. IF
#if ($myVar)
My variable value: $myVar
#else
My variable value is not set
#end
Start if with #if and end the statement with #end you can use #else which is optional
In Java to set parameter use:
context.put("myVar", "Prashant Gadekar");
2. Iterating Through List (FOREACH):
#foreach($element in $listVar)
Element $element
#end
In java use following code:
ArrayList list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
context.put("listVar", $list);
3. Iterating through Map
#foreach($element in $mapVar.entrySet())
Map key : $element.key
Map value : $element.value
#end
In java use:
HashMap map = new HashMap();
map.put("Key1", "Val1");
map.put("Key2", "Val2");
map.put("Key3", "Val3");
map.put("Key4", "Val4");
context.put("mapVar", map);
4. Iterating through array(FOREACH)
#foreach($i in [0..10])
Serial Number $i
#end
5. Computing in VTL (SET):
#set($myVar = 0)
My variable value $myVar
6. Converting a template to string
Template template = Velocity.getTemplate(tmplname);
StringWriter sw = new StringWriter();
if (context == null) {
context = new VelocityContext();
}
template.merge(context, sw);
sw.close();
String output = sw.toString();
No comments:
Post a Comment