← Complete Projects

阅读中文版本

Build a Text Template Rendering Library

A small template engine that renders placeholders, conditionals, and loops into text, escapes HTML on demand, and ships both a library API and a CLI.

intermediate~5 hnodejstemplatelibrarycli

Project goal

Build a template engine that compiles a template string into a render function, supports variable interpolation, if blocks, and loops, and offers an HTML-escaping mode.

Final features

  • Interpolate variables with a compile step that parses the template once.
  • Support if and else blocks with truthiness evaluation.
  • Support loops over arrays with access to the item and index.
  • Escape values in HTML mode and leave them raw in text mode.
  • Expose the engine as a library and a file-based CLI.

Architecture

A compiler tokenises the template into text and tag tokens, then emits a render function from those tokens; a runtime provides the variable lookup, truthiness, and escaping helpers; and the CLI reads a template and a JSON context and writes the rendered output. Compilation is separated from rendering so a template is parsed once.

Prerequisites

  • Node.js 20 LTS or later
  • Understanding of string parsing and closures
  • Basic familiarity with templating concepts

Dependencies

  • node >=20 — File system access and the CLI entry point
  • vitest ^2.1.0 — Compiler and runtime tests

Directory structure

template-engine/
├── src/
│   ├── tokenize.js
│   ├── compile.js
│   ├── runtime.js
│   └── cli.js
├── test/
│   ├── compile.test.js
│   └── runtime.test.js
└── package.json

Phases

1. Tokenizer

Split a template into text and tag tokens, recognising interpolation, if, and loop tags.

Files: src/tokenize.js

export function tokenize(source) {
  const tokens = [];
  const re = /\{\{\s*([#/]?)([^}]+?)\s*\}\}/g;
  let last = 0;
  let match;
  while ((match = re.exec(source))) {
    if (match.index > last) tokens.push({ type: 'text', value: source.slice(last, match.index) });
    const [, marker, expr] = match;
    if (marker === '#') tokens.push({ type: 'block', name: expr.trim() });
    else if (marker === '/') tokens.push({ type: 'endblock', name: expr.trim() });
    else tokens.push({ type: 'var', path: expr.trim() });
    last = re.lastIndex;
  }
  if (last < source.length) tokens.push({ type: 'text', value: source.slice(last) });
  return tokens;
}

Expected behavior: Plain text around tags becomes text tokens, an interpolation becomes a var token, and block open and close tags are distinguished by their markers.

2. Compiler

Turn tokens into a render function that handles interpolation, if blocks, and loops.

Files: src/compile.js

import { tokenize } from './tokenize.js';

export function compile(source, { escape = true } = {}) {
  const tokens = tokenize(source);
  const lines = [];
  const stack = [];
  for (const token of tokens) {
    if (token.type === 'text') lines.push('out.push(' + JSON.stringify(token.value) + ');');
    else if (token.type === 'var') {
      const expr = 'lookup(ctx, ' + JSON.stringify(token.path) + ')';
      lines.push('out.push(' + (escape ? 'esc(' + expr + ')' : expr) + ');');
    } else if (token.type === 'block') {
      const [kind, arg] = token.name.split(/\s+/, 2);
      if (kind === 'if') { lines.push('if (truthy(' + arg + ')) {'); stack.push('if'); }
      else if (kind === 'each') {
        lines.push('(lookup(ctx, ' + JSON.stringify(arg) + ') || []).forEach((item, i) => {');
        lines.push('ctx = { ...ctx, item, index: i };');
        stack.push('each');
      }
    } else if (token.type === 'endblock') { lines.push('}'); stack.pop(); }
  }
  return new Function('ctx', 'lookup', 'truthy', 'esc', 'const out = [];\n' + lines.join('\n') + '\nreturn out.join("");');
}

Expected behavior: A template with an if and a loop compiles without unbalanced braces, and rendering the compiled function produces the expected text.

3. Runtime helpers

Provide path lookup, truthiness, and HTML escaping used by compiled templates.

Files: src/runtime.js

export function lookup(scope, path) {
  return path.split('.').reduce((value, key) => (value == null ? undefined : value[key]), scope);
}

export function truthy(value) {
  if (Array.isArray(value)) return value.length > 0;
  return Boolean(value);
}

export function escapeHtml(value) {
  return String(value ?? '')
    .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

Expected behavior: Lookup resolves a nested path or returns undefined for a missing key, an empty array is falsy, and escaping converts angle brackets to entities.

4. Rendering context

Wire compile and runtime into one render call that takes a template and a context object.

Files: src/render.js

import { compile } from './compile.js';
import { lookup, truthy, escapeHtml } from './runtime.js';

export function render(template, context, options = {}) {
  const fn = compile(template, options);
  const esc = options.escape === false ? (v) => String(v ?? '') : escapeHtml;
  return fn(context, lookup, truthy, esc);
}

export function createRenderer(template, options = {}) {
  const fn = compile(template, options);
  const esc = options.escape === false ? (v) => String(v ?? '') : escapeHtml;
  return (context) => fn(context, lookup, truthy, esc);
}

Expected behavior: Render with escaping turns a script tag into entities, render with escape false leaves it raw, and createRenderer reuses the compiled function across calls.

5. CLI

Read a template file and a JSON context file, render, and write the output to stdout or a file.

Files: src/cli.js

import { readFile, writeFile } from 'node:fs/promises';
import { render } from './render.js';

const [templatePath, contextPath, outPath] = process.argv.slice(2);
if (!templatePath || !contextPath) {
  console.error('usage: render <template> <context.json> [out]');
  process.exit(1);
}
const template = await readFile(templatePath, 'utf8');
const context = JSON.parse(await readFile(contextPath, 'utf8'));
const output = render(template, context, { escape: outPath?.endsWith('.html') });
if (outPath) await writeFile(outPath, output);
else process.stdout.write(output);

Expected behavior: Rendering a fixture template to stdout prints the substituted text, and a missing argument exits with code 1 and a usage line.

6. Tests and hardening

Cover tokenizing, compiling, escaping, and the CLI, then fix any failure the tests reveal.

Files: test/compile.test.js

import { render } from '../src/render.js';

test('interpolates, escapes, and loops', () => {
  const tpl = 'Hi {{name}}!{{#each items}} {{item}}{{/each}}';
  expect(render(tpl, { name: 'Sam', items: ['a', 'b'] }, { escape: false })).toBe('Hi Sam! a b');
});

test('html mode escapes values', () => {
  expect(render('{{x}}', { x: '<b>' })).toBe('&lt;b&gt;');
});

test('if block honours emptiness', () => {
  expect(render('{{#if items}}yes{{/if}}', { items: [] }, { escape: false })).toBe('');
});

Expected behavior: The compile suite passes, an empty array makes an if block render nothing, and HTML mode escapes interpolated values.

Testing

Run npx vitest. Tokenizer tests cover plain text, interpolations, and malformed tags. Compile tests assert that a variable, an if block, and a loop render correctly, and that HTML mode escapes a script tag while text mode leaves it. A CLI test renders a fixture template with a JSON context and asserts the output.

Troubleshooting

Nested loops shadow the outer item variable

Track the previous binding when entering a loop and restore it on exit; a shared context object makes inner loops clobber the outer item by accident.

A missing variable renders the word undefined

Coerce null and undefined to an empty string in the escaping helper; a template should degrade to blank rather than leak an implementation detail.

An unclosed block consumes the rest of the file

Validate that the block stack is empty at the end of compilation and throw; silent truncation is far worse than a loud error.

Deployment

Use the library to generate emails or reports inside another program, or run the CLI in a build step to render static pages from templates and data. The compiled function can be cached per template for repeated rendering.

Known limitations

  • The compiler emits a function via new Function, which requires the template itself to be trusted.
  • There is no whitespace control syntax, so loop tags can leave stray spaces in the output.

Project overview

A template engine is a compact compiler problem: tokenise, parse, and emit a function. Building a small one teaches closures and string handling better than any abstract exercise, and the result is genuinely useful for generating emails and reports.

The engine compiles a template once into a render function, supports interpolation, conditionals, and loops, and switches escaping behaviour between HTML and plain text.

The compiler walks tokens and pushes string fragments and expressions onto a list, then joins them into a function body:

export function compile(source, { escape = true } = {}) {
  const tokens = tokenize(source);
  const body = tokens.map((token) => {
    if (token.type === 'text') return 'out.push(' + JSON.stringify(token.value) + ');';
    if (token.type === 'var') {
      const expr = 'lookup(ctx, ' + JSON.stringify(token.path) + ')';
      return 'out.push(' + (escape ? 'esc(' + expr + ')' : expr) + ');';
    }
    return '';
  }).join('\n');
  return new Function('ctx', 'lookup', 'esc', 'const out = [];\n' + body + '\nreturn out.join("");');
}

Compiling to a function once means rendering the same template for many records pays the parse cost a single time.

Setup

The engine has no runtime dependencies; the compiler is the entire value proposition and stays readable.

Dependency Version Why it is here
node >=20 File system access and the CLI entry point
vitest ^2.1.0 Compiler and runtime tests

Create the project and install:

mkdir template-engine && cd template-engine
npm init -y
npm install -D vitest@^2.1.0

Configure the CLI and tests in package.json:

{
  "name": "template-engine",
  "type": "module",
  "scripts": {
    "render": "node src/cli.js",
    "test": "vitest run"
  }
}

Keep example templates and context JSON files in a fixtures directory so CLI tests have inputs without inline strings.

Phase 1: Tokenizer

Split a template into text and tag tokens, recognising interpolation, if, and loop tags. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.

export function tokenize(source) {
  const tokens = [];
  const re = /\{\{\s*([#/]?)([^}]+?)\s*\}\}/g;
  let last = 0;
  let match;
  while ((match = re.exec(source))) {
    if (match.index > last) tokens.push({ type: 'text', value: source.slice(last, match.index) });
    const [, marker, expr] = match;
    if (marker === '#') tokens.push({ type: 'block', name: expr.trim() });
    else if (marker === '/') tokens.push({ type: 'endblock', name: expr.trim() });
    else tokens.push({ type: 'var', path: expr.trim() });
    last = re.lastIndex;
  }
  if (last < source.length) tokens.push({ type: 'text', value: source.slice(last) });
  return tokens;
}

Acceptance for this phase: Plain text around tags becomes text tokens, an interpolation becomes a var token, and block open and close tags are distinguished by their markers.

Phase 2: Compiler

Turn tokens into a render function that handles interpolation, if blocks, and loops. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.

import { tokenize } from './tokenize.js';

export function compile(source, { escape = true } = {}) {
  const tokens = tokenize(source);
  const lines = [];
  const stack = [];
  for (const token of tokens) {
    if (token.type === 'text') lines.push('out.push(' + JSON.stringify(token.value) + ');');
    else if (token.type === 'var') {
      const expr = 'lookup(ctx, ' + JSON.stringify(token.path) + ')';
      lines.push('out.push(' + (escape ? 'esc(' + expr + ')' : expr) + ');');
    } else if (token.type === 'block') {
      const [kind, arg] = token.name.split(/\s+/, 2);
      if (kind === 'if') { lines.push('if (truthy(' + arg + ')) {'); stack.push('if'); }
      else if (kind === 'each') {
        lines.push('(lookup(ctx, ' + JSON.stringify(arg) + ') || []).forEach((item, i) => {');
        lines.push('ctx = { ...ctx, item, index: i };');
        stack.push('each');
      }
    } else if (token.type === 'endblock') { lines.push('}'); stack.pop(); }
  }
  return new Function('ctx', 'lookup', 'truthy', 'esc', 'const out = [];\n' + lines.join('\n') + '\nreturn out.join("");');
}

Acceptance for this phase: A template with an if and a loop compiles without unbalanced braces, and rendering the compiled function produces the expected text.

Phase 3: Runtime helpers

Provide path lookup, truthiness, and HTML escaping used by compiled templates. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.

export function lookup(scope, path) {
  return path.split('.').reduce((value, key) => (value == null ? undefined : value[key]), scope);
}

export function truthy(value) {
  if (Array.isArray(value)) return value.length > 0;
  return Boolean(value);
}

export function escapeHtml(value) {
  return String(value ?? '')
    .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

Acceptance for this phase: Lookup resolves a nested path or returns undefined for a missing key, an empty array is falsy, and escaping converts angle brackets to entities.

Phase 4: Rendering context

Wire compile and runtime into one render call that takes a template and a context object. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.

import { compile } from './compile.js';
import { lookup, truthy, escapeHtml } from './runtime.js';

export function render(template, context, options = {}) {
  const fn = compile(template, options);
  const esc = options.escape === false ? (v) => String(v ?? '') : escapeHtml;
  return fn(context, lookup, truthy, esc);
}

export function createRenderer(template, options = {}) {
  const fn = compile(template, options);
  const esc = options.escape === false ? (v) => String(v ?? '') : escapeHtml;
  return (context) => fn(context, lookup, truthy, esc);
}

Acceptance for this phase: Render with escaping turns a script tag into entities, render with escape false leaves it raw, and createRenderer reuses the compiled function across calls.

Phase 5: CLI

Read a template file and a JSON context file, render, and write the output to stdout or a file. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.

import { readFile, writeFile } from 'node:fs/promises';
import { render } from './render.js';

const [templatePath, contextPath, outPath] = process.argv.slice(2);
if (!templatePath || !contextPath) {
  console.error('usage: render <template> <context.json> [out]');
  process.exit(1);
}
const template = await readFile(templatePath, 'utf8');
const context = JSON.parse(await readFile(contextPath, 'utf8'));
const output = render(template, context, { escape: outPath?.endsWith('.html') });
if (outPath) await writeFile(outPath, output);
else process.stdout.write(output);

Acceptance for this phase: Rendering a fixture template to stdout prints the substituted text, and a missing argument exits with code 1 and a usage line.

Phase 6: Tests and hardening

Cover tokenizing, compiling, escaping, and the CLI, then fix any failure the tests reveal. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.

import { render } from '../src/render.js';

test('interpolates, escapes, and loops', () => {
  const tpl = 'Hi {{name}}!{{#each items}} {{item}}{{/each}}';
  expect(render(tpl, { name: 'Sam', items: ['a', 'b'] }, { escape: false })).toBe('Hi Sam! a b');
});

test('html mode escapes values', () => {
  expect(render('{{x}}', { x: '<b>' })).toBe('&lt;b&gt;');
});

test('if block honours emptiness', () => {
  expect(render('{{#if items}}yes{{/if}}', { items: [] }, { escape: false })).toBe('');
});

Acceptance for this phase: The compile suite passes, an empty array makes an if block render nothing, and HTML mode escapes interpolated values.

Testing strategy

Run npx vitest. Tokenizer tests cover plain text, interpolations, and malformed tags. Compile tests assert that a variable, an if block, and a loop render correctly, and that HTML mode escapes a script tag while text mode leaves it. A CLI test renders a fixture template with a JSON context and asserts the output.

The malformed-tag test matters because a template engine that silently drops bad syntax hides typos until a page renders blank in production.

Extending the project

Filters such as date formatting, partials, and layout inheritance are additions to the tokenizer and runtime. Because compilation emits a plain function, the runtime grows without touching the parser.