Home Apachevelocity Use Velocity to generate HTML document



Use Velocity to generate HTML document
Posted on: August 28, 2008 at 12:00 AM
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

Related Tags for Use Velocity to generate HTML document:
htmlcusingthisvelocityshowexampletoexamciwsshgenerateeitdocociinmlmntlocmehowratedoxaxampsathtmismplcityssthshopleplo


More Tutorials from this section

Ask Questions?    Discuss: Use Velocity to generate HTML document  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.