Knowledge Walls
John Peter
Pune, Maharashtra, India
How to use not specified velocity context variable value as empty in VTL with Example
7593 Views
$!{identifier} 
In VTL Output returns variable name with dollar. If velocity context is not added with the velocity context MapValueList.

Instead of using
$username
This will return $username as output when value not specified for username context.

Use
$!username or $!{username}
If username not in velocity context also this takes empty string as input.
Example
import java.io.StringWriter;

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

public class Example {
    public static void main(String args[]){
        VelocityEngine ve = new VelocityEngine();
        ve.init();
         
        Template t = ve.getTemplate("velocitytemplate.vm");
         
        VelocityContext vc = new VelocityContext();
        
        StringWriter sw = new StringWriter();
        t.merge(vc, sw);
         
        System.out.println(sw);
    }
}
Velocitytemplate.vm 
UserDetails
-----------
Username is $username.
Username is $!username.
Username is $!{username}.
Output 
UserDetails
-----------
Username is $username.
Username is .
Username is .
Best Lessons of "Java Apache Velocity Examples"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details