07 April 2011

Apache velocity : VTL: Directives

Apache velocity directives and how to use them

1. IF

   #if ($myVar)
     My variable value: $myVar
     My variable value is not set

  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

   In java use following code:

   ArrayList list = new ArrayList();
   context.put("listVar", $list);

3. Iterating through Map

   #foreach($element in $mapVar.entrySet())
      Map key : $element.key
      Map value : $element.value

   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

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);
       String output = sw.toString();

No comments:

Post a Comment