-
Notifications
You must be signed in to change notification settings - Fork 0
Template Engines
Robin Drew edited this page Feb 27, 2025
·
12 revisions
A template engine allows a developer to apply dynamic data to text templates to generate documents like HTML.
The first step to using Velocity is to configure the template engine.
// Create the templating engine
VelocityEngine engine = new VelocityEngine();
// Basic properties
engine.setProperty("input.encoding", "UTF-8"); // This is default
engine.setProperty("directive.foreach.maxloops", 1000);
// Loading templates from files ...
// A list of paths on which to locate template files
engine.setProperty("file.resource.loader.path", pathList);
// Disable caching to be able to edit/reload templates while application is running (useful while developing app)
engine.setProperty("file.resource.loader.cache", false);
engine.init();Once the engine is ready, we need to be able to load templates and apply data to them.
// Load the template by its path
Template template = engine.getTemplate("velocity/Test.template", "UTF-8");
// Populate a context with data to be applied to the template
VelocityContext context = new VelocityContext();
context.put("message", "Hello World");
// Finally merge the template with context and provide a Writer for the output
Writer writer = new StringWriter();
template.merge(context, writer);Useful links: