tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Template Engines > Velocity > Load Template from Stream

Load Template from Stream 

Apache Velocity is a free, simple and powerful template engine written in 100% pure Java. This requires the libraries velocity-1.7.jar, oro-2.0.8.jar, commons-lang-2.4.jar, commons-collections-3.2.1.jar, commons-logging-1.1.jar, log4j-1.2.12.jar to be in classpath. The following example shows loading a Velocity template from an input stream.

File Name  :  
/VELOCITY001/config/basic.vm 

File Name  :  
com/bethecoder/tutorials/velocity/tests/LoadTemplateFromStreamTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.velocity.tests;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;

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

public class LoadTemplateFromStreamTest {

  /**
   @param args
   */
  public static void main(String[] args)  {

        /**
         * Prepare context data
         */
        VelocityContext context = new VelocityContext();
        context.put("site""BE THE CODER");
        context.put("tutorial_name""Apache Velocity");

        StringWriter swOut = new StringWriter();
        Reader templateReader = new BufferedReader(
                  new InputStreamReader(getStream("basic.vm")));
        /**
         * Merge data and template
         */
        Velocity.evaluate(context, swOut, "log tag name", templateReader);
        System.out.println(swOut);
  }
  
  private static InputStream getStream(String resource) {
    return LoadTemplateFromStreamTest.class.getClassLoader().getResourceAsStream(resource);
  }
}
   

It gives the following output,
Apache Velocity tutorials by BE THE CODER



 
  


  
bl  br