Wednesday, 12 December 2012

Velocity Template Tutorial_3

DIRECTIVES :
  • Always start with the character “#”.
  • Different directives are used for different purpose in which most important and most widely used are #set, #if, #elseif, #else, #end, #foreach, #parse, #include, #macro.
SET Directive:
  • Used to assign or set a value to variable.
  • Syntax :
     #set(refernceValue)
       eg: #set($userName =”vignesh”)
  • In set directive or any where in VTL String always start with single or double quotes (''/””)
PROGRAMMING :
REQUIRED PACKAGES :
  • 1.velocity-1.6.2.jar
  • 2.commons-collections-3.2.1.jar
  • 3.commons-lang-2.4.jar
  • 4.oro-2.0.8.jar
TO Download this files  click here


JAVA-FILE :

import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class Directives {

public static void main(String args[]) throws Exception{
/*STEP 1 :Initialise VelocityTemplate Engine */
Velocity.init();
/*STEP 2: Create the template object*/
Template template = Velocity.getTemplate("directives.vm");
/*STEP 3: Create VelocityContext */
VelocityContext context = new VelocityContext();
context.put("sex","male");
context.put("name", "ram");
context.put("password", "ram");
StringWriter writer = new StringWriter();
/*STEP 4: Process the template and write the o/p to stream*/
template.merge(context, writer);
/*STEP 6: Show the output */
System.out.println(writer);
}
}

directives.vm-TEMPLATE FILE

## SET directive
#set($userName = "vignesh")   ----->STEP:1

____________________________
|                           |
| UserName : $userName      | ------->STEP:2
| Password : $userName      | ------->STEP:3
|                           |
| You are authenticated     |
|___________________________|
#*--------------------------------------------------*#
OUTPUT:
 ____________________________
|                           |
| UserName : vignesh        |
| Password : vignesh        |
|                           |
| You are authenticated     |
|___________________________|
EXPLANATION :
STEP:1 --> setting the value “vignesh” for the variable “username”
STEP:2&3 --> Using the variable
Running the program we get the output which replaces $username with “vignesh”

IF Directive :
  • Control statement same as JAVA if statement
  • Syntax :
     #if(condition)
        value to be printed
     #end
     Example: #if($isRavi)
                Iam ravi 
              #end
  • 'if' directive must end with '#end' directive
PROGRAMMING :
JAVA-FILE :

import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class Directives {

public static void main(String args[]) throws Exception{
/*STEP 1 :Initialise VelocityTemplate Engine */
Velocity.init();
/*STEP 2: Create the template object*/
Template template = Velocity.getTemplate("directives.vm");
/*STEP 3: Create VelocityContext */
VelocityContext context = new VelocityContext();
StringWriter writer = new StringWriter();
/*STEP 4: Process the template and write the o/p to stream*/
template.merge(context, writer);
/*STEP 6: Show the output */
System.out.println(writer);
}
}

directives.vm-TEMPLATE FILE
## SET directive
#set($isVignesh = true) --->STEP:1

#*--------------------------------------------------*#
## IF and END directive use
#if($isVignesh)         --->STEP:2
I am vignesh
#end
#*--------------------------------------------------*#
OUTPUT:
I am vignesh
EXPLANATION :
STEP:1---> set the value for isVignesh as true
STEP:2---> Check the condition inside the if statement then the result is true so “I am vignesh” is printed


ELSE DIRECTIVE :
  • Control statement same as JAVA else statement
  • Syntax :
    #if(condition)
      value to be printed
    #else
       value to be printed
    #end
     Example: #if($isRavi)
                 Iam ravi 
              #else 
                I am ram
              #end
  • Must end with “#end” directive.
PROGRAMMING :
JAVA-FILE :

import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class Directives {

public static void main(String args[]) throws Exception{
/*STEP 1 :Initialise VelocityTemplate Engine */
Velocity.init();
/*STEP 2: Create the template object*/
Template template = Velocity.getTemplate("directives.vm");
/*STEP 3: Create VelocityContext */
VelocityContext context = new VelocityContext();
context.put("sex","male");           // ------>STEP:1
StringWriter writer = new StringWriter();
/*STEP 4: Process the template and write the o/p to stream*/
template.merge(context, writer);
/*STEP 6: Show the output */
System.out.println(writer);
}
}
directives.vm-TEMPLATE FILE
#*--------------------------------------------------*#
## IF and ELSE directive use
#if($sex == 'male')       ## ----->STEP:2 $sex get value from JAVA code
Hi vignesh, your gender is male
#else
Hi vignesh, your gender is female
#end
#*--------------------------------------------------*#
OUTPUT

Hi vignesh, your gender is male
EXPLANATION :
STEP:1---> setting sex as male.
STEP:2---> $sex get value from JAVA code or simply put from step 1
Since the value of sex is set to male in step 1 the output is “Hi vignesh, your gender is male”

ELSEIF Directive :
  • Control statement same as JAVA else-if statement
  • Syntax :
      #if(condition)
        value to be printed
      #elseif(condition)
        another value to be printed
      #else
        value to be printed
      #end
        Example: #if($isRavi)
                    Iam ravi
                 #elseif($isRam)
                     I am ram 
                 #else 
                     Who are you?
                  #end
  • Must end with “#end” directive.
FOREACH DIRECTIVE:
  • Loop statement same as JAVA foreach loop
  • Syntax :
    #foreach(varaible in list/array)
       value to be printed
    #end
    EXAMPLE : #foreach($i in [1....5])
               $i
              #end
  • Must end with “#end” directive.
  • We can declare array inside foreach like [1,2,3,4,5] or [1...5] but don't use syntax as [1,2,3...7]

PROGRAMMING :
JAVA-FILE :

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class ForEachDirectives {

public static void main(String args[]) throws Exception{
/*STEP 1 :Initialise VelocityTemplate Engine */
Velocity.init();
/*STEP 2: Create the template object*/
Template template = Velocity.getTemplate("for_each_directives.vm");
/*STEP 3: Create list for iteration*/
Map<String,Integer> nameAndAge = new HashMap<String, Integer>();                 // ----> STEP:1
nameAndAge.put("vignesh",24);
nameAndAge.put("jagadeesh",25);
nameAndAge.put("pushparaja",26);
Map<String,String> companyNameAndCEO = new HashMap<String, String>();     // ---->STEP:2
companyNameAndCEO.put("tisya","RavidraMoorthy");
companyNameAndCEO.put("focus","vipual");
@SuppressWarnings("rawtypes")
List<Map> list = new ArrayList<Map>(); // ---->STEP:3
list.add(nameAndAge);
list.add(companyNameAndCEO);
/*STEP 3: Create VelocityContext */
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("details",list);
StringWriter writer = new StringWriter();
/*STEP 4: Process the template and write the o/p to stream*/
template.merge(velocityContext, writer);
System.out.println(writer);
}
}


for_each_directives.vm-TEMPLATE FILE
## FOREACH directive use case :Get values from java code
#foreach($detail in $details)     ## ---> STEP:4
#set($map = $detail)              ## ---> STEP:5
#set($mapKeys= $map.keySet())     ## ----> STEP:6
#foreach($keyValue in $mapKeys)   ##---->  STEP:7
Key : $keyValue | Value : $map.get($keyValue) ## -->STEP:8
#end
#end
#*--------------------------------------------------*#
OUTPUT :
Key : vignesh | Value : 24
Key : jagadeesh | Value : 25
Key : pushparaja | Value : 26
Key : focus | Value : vipual
Key : tisya | Value : RavidraMoorthy
EXPLANATION :

STEP:1&2 --> Creating two maps and putting values into it
STEP:3 --> Creating the list and adding map to the list
STEP:4 --> Creating a foreach loop and $details denotes values from java-cost which is list which we added in step three
STEP:5 ---> Taking the list value which is map and storing that in $map variable
STEP:6 ---> Taking the key from map and storing that in $mapKeys variable
STEP:7 --->Creating a foreach and iterating over the keys.
STEP:8. ---> By using key we are retriving the value from map.

PROGRAMMING : USING ARRAYS:

JAVA-FILE :
public class Directives {
public static void main(String args[]) throws Exception{
/*STEP 1 :Initialise VelocityTemplate Engine */
Velocity.init();
/*STEP 2: Create the template object*/
Template template = Velocity.getTemplate("directives.vm");
/*STEP 3: Create VelocityContext */
VelocityContext context = new VelocityContext();
StringWriter writer = new StringWriter();
/*STEP 4: Process the template and write the o/p to stream*/
template.merge(context, writer);
/*STEP 6: Show the output */
System.out.println(writer);
}
}

directives.vm-TEMPLATE FILE
## FOREACH directive use
#foreach($name in [1..10]) ## don't use [1,2,3..10]
$name
#end
OUTPUT:
1
2
3
4
5
6
7
8
9
10

INCLUDE DIRECTIVE:
  • Takes content from template file and include that content into another template file.
  • While including the content to another template no parsing is done even when there is some VTL.
  • SYNTAX :
      #include(filelocation)
    EXAMPLE : #include(./src/another_file.vm)
  • Can add content from any kind of content like XML or HTML contents into another file.
PROGRAMMING :
JAVA-FILE:

import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class IncludeDirective {
public static void main(String args[]) throws Exception{
/*STEP 1 :Initialise VelocityTemplate Engine */
Velocity.init();
/*STEP 2: Create the template object*/
Template template = Velocity.getTemplate("include_dirtective.vm");
/*STEP 3: Create VelocityContext */
VelocityContext context = new VelocityContext();
context.put("name","vignesh"); // =====>STEP:1
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer);
}
}
include_dirtective.vm-TEMPLATE FILE
## Include directive example

#include("include_directive_iclude_file.vm") ## ===> STEP:2
Awesome we have included the external vm file in to this file 
 
include_directive_iclude_file.vm -TEMPLATE FILE
This is from external file but i am included in some file here i am not parsed by VelocityEngine ,means if there is any Velocity Template language then their contents are not rendered
For example $name will be rendered as "$name" itself ## ===> STEP:3
OUTPUT:
[ This is from external file but i am included in some file here i am not parsed by VelocityEngine ,means if there is any Velocity Template language then their contents are not rendered
For example $name will be rendered as "$name" itself ] ## ===> STEP:4

Awesome we have included the external vm file in to this file
EXPLANATION:
STEP:1 ---> We have put key value as “name” and “vignesh”
STEP:2 ---> Included another file named “include_directive_iclude_file.vm
STEP:3 ---> We have used VTL inside the template file “include_directive_iclude_file.vm”[File going whose contents are going to be added in “include_dirtective.vm”]
STEP:4 ---> we have included the contents of include_directive_iclude_file.vm into include_dirtective.vm file but note that “$name” has not modified even though we used VTL and set the value of “$name” in java code this is because we used #include directive.

PARSE DIRECTIVE :
  • Takes content from template file and add that content into another template file
  • While adding the content to another template parsing is done when VTL is found in the file.
  • SYNTAX :#parse(filelocation)
      EXAMPLE : #parse(./src/another_file.vm)
  • Can add content from any kind of content like XML or HTML contents into another file.
  • Simple put #parse = #include + process template file.
PROGRAMMING :
JAVA-FILE:

import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class ParseDirective {
public static void main(String args[]) throws Exception{
/*STEP 1 :Initialise VelocityTemplate Engine */
Velocity.init();
/*STEP 2: Create the template object*/
Template template = Velocity.getTemplate("parse_dirtective.vm");
/*STEP 3: Create VelocityContext */
VelocityContext context = new VelocityContext();
context.put("name","vignesh"); // =====>STEP:1
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer);
}
}
parse_dirtective.vm-TEMPLATE FILE
## Parse directive example

#parse("parse_directive_iclude_file.vm") ## ===> STEP:2
Awesome we have included the external vm file in to this file 
 
parse_directive_iclude_file.vm -TEMPLATE FILE
This is from external file but i am included in some file here i am not parsed by VelocityEngine ,means if there is any Velocity Template language then their contents are not rendered
For example “\$name” will be rendered as "vignesh"
Render vignesh -> $name ## ===> STEP:3
OUTPUT:
[ This is from external file but i am included in some file here i am not parsed by VelocityEngine ,means if there is any Velocity Template language then their contents are not rendered
For example "$name" will be rendered as "vignesh"
Render vignesh -> vignesh ] ## ===>STEP: 4

Awesome we have included the external vm file in to this file
EXPLANATION:
STEP:1 ---> We have put key value as “name” and “vignesh”
STEP:2 ---> Included another file named “parse_directive_iclude_file.vm
STEP:3 ---> We have used VTL inside the template file “parse_directive_iclude_file.vm”[File going whose contents are going to be added in “parse_dirtective.vm”]
STEP:4 ---> we have included the contents of parse_directive_iclude_file.vm into parse_dirtective.vm file and note that “Render vignesh -> $name” has modified to “Render vignesh -> vignesh , this is because we used #parse directive.

MACRO DIRECTIVE :
  • Used to craete a function/method like functionality in template file.[NOTE : simple put its a method in VTL as like method in java]
  • Create a macro in a template and we can call any times we want that macro , hence code reduction.
  • Syntax[NOTE: Let us think macro as methods which will be easy for us] #macro(macroName/methodName macroArguments)
         values to be printed
    #end
    EXAMPLE:
    #macro(createTable items)
        //Here createtable is method/macro name and items is macro argument 
          #foreach(item in items) 
         #set($i = 1)
          <table> 
            <tr><td>$i</td>
               <td>$item</td></tr>
          </table>
         $i= $i+1 
        #end 
     #end
    NOW FOR CALLING THIS MACRO USE THIS SYNTAX #createTable(itemListObject)
  • Must end with #end directive.
PROGRAMMING :
JAVA-FILE:
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class MacroDirective {

public static void main(String args[]) throws Exception{
/*STEP 1 :Initialise VelocityTemplate Engine */
Velocity.init();
/*STEP 2: Create the template object*/
Template template = Velocity.getTemplate("macro_directive.vm");
/*STEP 3: Create VelocityContext */
VelocityContext context = new VelocityContext();
Map<String,Integer> nameAndAge = new HashMap<String, Integer>(); //===>STEP:1
nameAndAge.put("vignesh",24);
nameAndAge.put("jagadeesh",25);
nameAndAge.put("pushparaja",26);
context.put("nameAndAgeMap", nameAndAge); //====>STEP:2
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer);
}
}
macro_directive.vm-TEMPLATE FILE

## Macro directive example

##Here createTable is macroNAme and $nameAndAgeMap is macro Argument . we can have any number of arguments
#macro(createTable $nameAndAgeMap) ## ===>STEP:3
#set($names = $nameAndAgeMap.keySet())
#foreach($name in $names)
| $name |$nameAndAgeMap.get($name)|
#end
_____________________________________
#end
#createTable($nameAndAgeMap) ## calling the macro ===>STEP:4
#createTable($nameAndAgeMap) ## calling the macro ====>STEP:5

OUTPUT:

| vignesh |24|
| jagadeesh |25|
| pushparaja |26|
_____________________________________
| vignesh |24|
| jagadeesh |25|
| pushparaja |26|
_____________________________________

EXPLANATION :
STEP:1&2--> Creating and adding map and their values to context.
STEP:3 ----> Creating a macro named “createTable” with arguments “$nameAndAgeMap” and inside this macro we are processing the values
STEP:4&5 -----> Calling the created macro by using the argument which it takes from java-code[step 1]


  • Macros can be created outside a template and we can call the template when ever necessary like creating a “.js”[javascript] file and using the function created in .js file in another HTML file.

    Note : If you find any thing which you can not understand or wrong please leave comments.I assure i will get back to you.

    NOTE : TO download the velocity tutorial in word format click here

2 comments: