Use Velocity to generate HTML document

Ads
 

Use Velocity to generate HTML document

This Example shows you how to generate HTML document using velocity.

This Example shows you how to generate HTML document using velocity.

Use Velocity to generate HTML document

     

This Example shows you how to generate HTML document using velocity. The method used in this example are described below:- 

1:- Initialize velocity run time engine through method  init().
2:- Create object of VelocityContext Class.
3:- Create Template class object, Template  class object is used for controlling template methods and properties.

template.merge(context, writer): Merge method of the Template class is used here for merging  the VelocityContext class object to produce the output. Template class object is used for controlling template methods and properties.

In the HTMLdocument.vm file we will set products, bgcolor value and use these variable to generate HTML document

 

 

 

HTMLdocument.java:

import java.io.*;

import org.apache.velocity.*;
import org.apache.velocity.app.*;
import org.apache.velocity.tools.generic.RenderTool;

public class HTMLdocument {

  public static void main(String[] argsthrows Exception {
  Velocity.init();
  Template template = Velocity.getTemplate("./src/HTMLdocument.vm");

  VelocityContext context = new VelocityContext();

  Writer writer = new StringWriter();
  template.merge(context, writer);

  System.out.println(writer);
  }
}

HTMLdocument.vm:
<html>
  <body>
  <table border="1">
  #set ($rowCount = 1)  
  #set ($products = ["one""two""three","four"])
  #foreach($product in $products)
  #if ($rowCount % == 0)
  #set ($bgcolor = "#FFFFFF")
  #else
  #set ($bgcolor = "#CCCCCC")  
  #end
  <tr>
  <td bgcolor="$bgcolor">$product</td>
  <td bgcolor="$bgcolor">$product</td>
  </tr>  
  #set ($rowCount = $rowCount + 1)
  #end
  </table>
  </body>
</html>

Output:
<html>
  <body>
  <table border="1">
  <tr>
  <td bgcolor="#CCCCCC">one</td>
  <td bgcolor="#CCCCCC">one</td>
  </tr>  
  <tr>
  <td bgcolor="#FFFFFF">two</td>
  <td bgcolor="#FFFFFF">two</td>
  </tr>  
  <tr>
  <td bgcolor="#CCCCCC">three</td>
  <td bgcolor="#CCCCCC">three</td>
  </tr>  
  <tr>
  <td bgcolor="#FFFFFF">four</td>
  <td bgcolor="#FFFFFF">four</td>
  </tr>  
  </table>
  </body>
</html>

Download code

Ads

Tutorials   

Ads