How to use String as Velocity Template?

velocity template to generate json
velocity template tutorial
velocity string functions
velocity concatenate strings
velocity array
velocity template from string
apache velocity
velocity macro

What is the best way to create Velocity Template from a String?

I'm aware of Velocity.evaluate method where I can pass String or StringReader, but I'm curios is there a better way to do it (e.g. any advantage of creating an instance of Template).

There is some overhead parsing template. You might see some performance gain by pre-parsing the template if your template is large and you use it repeatedly. You can do something like this,

RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
StringReader reader = new StringReader(bufferForYourTemplate);
Template template = new Template();

 * The following line works for Velocity version up to 1.7
 * For version 2, replace "Template name" with the variable, template
template.setData(runtimeServices.parse(reader, "Template name")));


Then you can call template.merge() over and over again without parsing it everytime.

BTW, you can pass String directly to Velocity.evaluate().

How to use string as velocity template data with Example, 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  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.

The above sample code is working for me. It uses Velocity version 1.7 and log4j.

private static void velocityWithStringTemplateExample() {
    // Initialize the engine.
    VelocityEngine engine = new VelocityEngine();
    engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute");
    engine.setProperty("runtime.log.logsystem.log4j.logger", LOGGER.getName());
    engine.setProperty(Velocity.RESOURCE_LOADER, "string");
    engine.addProperty("string.resource.loader.class", StringResourceLoader.class.getName());
    engine.addProperty("string.resource.loader.repository.static", "false");
    //  engine.addProperty("string.resource.loader.modificationCheckInterval", "1");

    // Initialize my template repository. You can replace the "Hello $w" with your String.
    StringResourceRepository repo = (StringResourceRepository) engine.getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT);
    repo.putStringResource("woogie2", "Hello $w");

    // Set parameters for my template.
    VelocityContext context = new VelocityContext();
    context.put("w", "world!");

    // Get and merge the template with my parameters.
    Template template = engine.getTemplate("woogie2");
    StringWriter writer = new StringWriter();
    template.merge(context, writer);

    // Show the result.

A similar so question.

Apache Velocity Engine, The Velocity Template Language (VTL) is meant to be capable of using VTL to incorporate dynamic content in a web site. String values are always enclosed in quotes,  I have a list of strings in the memory. I want to load all of them as velocity templates during the application startup. How do I do it ? I know how to create template from a string from here: How to use String as Velocity Template? But I want to know how to load all template strings in one shot

This works in Velocity 2.1

// Initialize the engine
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.setProperty(Velocity.RESOURCE_LOADERS, "string");
velocityEngine.setProperty("resource.loader.string.class", StringResourceLoader.class.getName());

// Add template to repository
StringResourceRepository repository = StringResourceLoader.getRepository()
repository.putStringResource("hello_world", "Hello $w");

// Set parameters
VelocityContext context = new VelocityContext();
context.put("w", "world!");

// Process the template
StringWriter writer = new StringWriter();
velocityEngine.getTemplate('hello_world').merge( context, writer );


Apache Velocity Tools Usage Summary, propertyName (If this method can be treated as a bean property in Velocity, then it $esc.html( string ), escapes the characters in a string using HTML entities to evaluate the given strings as VTL (Velocity Template Language) using either a​  Probably should configure a VelocityEngine to use it and initialize the engine first with properties like these: resource.loader = string string.resource.loader.class = org.apache.velocity.runtime.resource.loader.StringResourceLoader – Nathan Bubna yesterday

Velocity 2 can be integrated into the JSR223 Java Scripting Language Framework which make another option to transform string as a template:

ScriptEngineManager manager = new ScriptEngineManager();
manager.registerEngineName("velocity", new VelocityScriptEngineFactory());
ScriptEngine engine = manager.getEngineByName("velocity");

System.setProperty(VelocityScriptEngine.VELOCITY_PROPERTIES, "path/to/");
String script = "Hello $world";
Writer writer = new StringWriter();
Object result = engine.eval(script);

Velocity - Velocity User Guide - Apache Velocity, When using the #set directive, string literals that are enclosed in #set( $​template = "$directoryRoot/$templateName" ) $template  How to use string as velocity template data with Example Examples of Java Apache Velocity Examples How to use #continue in foreach of Java apache velocity with Example

RuntimeServices rs = RuntimeSingleton.getRuntimeServices();            
StringReader sr = new StringReader("Username is $username");
SimpleNode sn = rs.parse(sr, "User Information");

Template t = new Template();

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

StringWriter sw = new StringWriter();
t.merge(vc, sw);


How to use String as Velocity Template?, Use String as Velocity Template. Code example extracted from Stack Overflow: RuntimeServices runtimeServices = RuntimeSingleton  How to use string as velocity template data with Example. How to use For loop in Java velocity with Example. How to use list object with foreach in Java Velocity

BE THE CODER > Template Engines > Velocity Examples > Load , Load Template from String. Apache Velocity is a free, simple and powerful template engine written in 100% pure Java. This requires  The core class of Velocity is the VelocityEngine. It orchestrates the whole process of reading, parsing and generating content using data model and velocity template. Simply put, here are the steps we need to follow for any typical velocity application: Initialize the velocity engine; Read the template; Put the data model in context object

Using the Velocity template engine, Velocity is a template engine written for Java. It allows us to take files (or strings) with embedded Velocity Template Language (VTL) code and  In the Pet Store example template, Velocity's introspection facility finds and invokes the Map's public Object get(String)method with the keys nameand price. We could access the same data in a different way by invoking the get(String)method directly in the template: $pet.get('name') for only $pet.get('price')

Introduction to Apache Velocity, Velocity Template Language (VTL) provides the simplest and The final value resulting from every reference is converted to a string To implement a web application, we need to use a servlet or servlet-based framework. How to use string as velocity template data with Example. How to use Else-If ladder in Java velocity with Example How to use #continue in foreach of Java apache

  • Exactly what I was looking for. Thanks. For other people's reference, runtimeServices is an instance of org.apache.velocity.runtime.RuntimeInstance
  • Missed one-line. For completeness, I added it.
  • +1 for the mention of Velocity.Evaluate since that's exactly what I was looking for.
  • Wow, this is a unique approach. how velocity engine load resource seems is internal implementation, could property "string.resource.loader.class" subject to change?
  • You seem to have a typo in Velocity.RESOURCE_LOADERS - should probably be Velocity.RESOURCE_LOADER.
  • The RuntimeConstants interface which is implemented by Velocity class has both constants - RESOURCE_LOADERS and RESOURCE_LOADER. RESOURCE_LOADERS was the one I tested with