Knowledge Walls
John Peter
Pune, Maharashtra, India
How to use string as velocity template data with Example
20647 Views
Hints 
String context value map example for basic velocity program to write username value into datapage.vm template via java.

VelocityEngine class is used to parse the Velocity template (vm) file. VelocityContext contians all the data which is needed to bind in (.vm) file. StringWriter stream writes the data into the stream.
Example
RuntimeServices rs = RuntimeSingleton.getRuntimeServices();            
StringReader sr = new StringReader("Username is $username");
SimpleNode sn = rs.parse(sr, "User Information");

Template t = new Template();
    t.setRuntimeServices(rs);
    t.setData(sn);
    t.initDocument();

VelocityContext vc = new VelocityContext();
vc.put("username", "John");

StringWriter sw = new StringWriter();
t.merge(vc, sw);
    
System.out.println(sw.toString());
Output 
Username is John
Previous Topics
Previous lessons of current book.
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