art-template

4.13.4 · active · verified Sun Apr 19

art-template is a high-performance JavaScript template engine designed for both Node.js and browser environments. It achieves near-JavaScript-limit rendering speeds through a 'scope pre-declared' optimization technique. The current stable version is 4.13.4, with a release cadence that addresses bugs, performance, and adds minor features, as seen in recent patch and minor releases (e.g., v4.13.0 for performance fixes, v4.13.2 for type definitions). Key differentiators include its extreme speed, debugging friendliness (accurate error positioning, breakpoint support with Webpack loader), support for template inheritance, sub-templates, and a small browser footprint (6KB). It integrates with popular frameworks like Express and Koa, and build tools like Webpack.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `art-template` with global defaults, register custom filters, compile a template string, and render it with provided data. It showcases basic templating features like variable output, looping, conditionals, and raw HTML output.

import template from 'art-template';

// 1. Configure global defaults (optional)
template.defaults.escape = false; // Disable HTML escaping for raw output

// 2. Define a template string
const templateString = `
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <title>{{ title }}</title>
  </head>
  <body>
    <h1>Hello, {{ name | capitalize }}!</h1>
    <p>Your items:</p>
    <ul>
      {{ each items }}
        <li>Item #{{ $index + 1 }}: {{ $value }}</li>
      {{ /each }}
    </ul>
    {{ if showFooter }}
      <footer>Rendered at: {{ date | dateFormat }}</footer>
    {{ /if }}
    <p>Raw HTML (if escape is disabled): {{ @rawHtml }}</p>
  </body>
  </html>
`;

// 3. Register a custom filter (optional)
template.defaults.imports.capitalize = (value: string) => {
  return value.charAt(0).toUpperCase() + value.slice(1);
};
template.defaults.imports.dateFormat = (date: Date) => {
  return date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
};


// 4. Compile the template (recommended for performance in production)
const render = template.compile(templateString);

// 5. Define data
const data = {
  title: 'Art Template Example',
  name: 'world',
  items: ['apple', 'banana', 'orange'],
  showFooter: true,
  date: new Date(),
  rawHtml: '<strong>This is bold!</strong>'
};

// 6. Render the template with data
const output = render(data);
console.log(output);

// You can also render directly without pre-compiling for simple cases (less efficient)
const directOutput = template(templateString, {
    title: 'Direct Render Example',
    name: 'test',
    items: ['one', 'two'],
    showFooter: false,
    date: new Date(),
    rawHtml: '<i>Italic!</i>'
});
// console.log(directOutput);

view raw JSON →