Velocity.js Template Engine

2.1.5 · active · verified Sun Apr 19

velocityjs is a JavaScript implementation of the Apache Velocity Template Language (VTL), providing a robust solution for server-side and client-side templating. The current stable version is 2.1.5, offering full compatibility with Java Velocity syntax. It distinguishes itself by separating template parsing into an Abstract Syntax Tree (AST) from the rendering phase, allowing for optimized compilation and execution. Key features include high performance, a lightweight footprint, and comprehensive support for VTL directives such as `#set`, `#foreach`, `#if`, and custom `#macro` definitions. While a specific release cadence isn't detailed, the library appears mature and stable, making it a reliable choice for projects needing VTL capabilities in a JavaScript environment.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic template rendering, the use of custom macros for directives like `#include`, and how to use the `parse` and `Compile` methods for pre-compilation and advanced configuration like HTML escaping.

import { render, parse, Compile } from 'velocityjs';

// Simple rendering
const result = render('Hello $name!', { name: 'World' });
console.log(result); // Output: Hello World!

// With macros and custom logic
const macros = {
  include: (path) => {
    // In a real application, you'd load content from 'path'
    // For this example, we'll simulate it.
    if (path === 'header.vm') {
      return '<h1>Welcome!</h1>';
    } else if (path === 'footer.vm') {
      return '<p>Copyright 2024</p>';
    } else {
      return `<!-- Error: ${path} not found -->`;
    }
  }
};
const template = '#include("header.vm") Hello $name! Today is $date. #include("footer.vm")';
const context = { name: 'Velocity.js User', date: new Date().toLocaleDateString() };
const renderedWithMacros = render(template, context, macros);
console.log(renderedWithMacros);

// Using Compile for performance or advanced parsing
const asts = parse('The answer is $answer.');
const compiledTemplate = new Compile(asts, { escape: true }); // Enable HTML escaping
const compiledResult = compiledTemplate.render({ answer: '<script>alert("XSS!")</script>' });
console.log(compiledResult); // Output: The answer is &lt;script&gt;alert(&quot;XSS!&quot;)&lt;/script&gt;

view raw JSON →