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

Context from Map 

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 creating Velocity context from a Map.

File Name  :  

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

import java.util.HashMap;
import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

public class ContextFromMapTest {

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

     * Initialize engine and get template
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath")
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        Template template = ve.getTemplate("context4mmap.vm");
         * Prepare context data
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("JAVA_HOME", System.getProperty("java.home"));
        dataMap.put("USER_HOME", System.getProperty("user.home"));
        VelocityContext context = new VelocityContext(dataMap);
         * Merge data and template
        StringWriter swOut = new StringWriter();
        template.merge(context, swOut);

It gives the following output,
JAVA HOME : C:\Program Files\Java\jdk1.6.0_10\jre
USER HOME : C:\Documents and Settings\vsudhakar001


bl  br