← 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 project is deliberately sized so that every stage ships something you can run: the first phase produces a working command or endpoint, and each later phase adds one capability without forcing a rewrite of what came before. That property — always runnable, never half-migrated — is what makes the tutorial usable as a weekend build rather than a sketch that only works once the final commit lands.

The finished tool carries no hidden services and no hosted dependencies. Everything it needs lives in the repository and a machine with the stated runtime, so a reader can clone, install, run the tests, and trust that the behaviour they see locally is the behaviour the tutorial promised. Where a real deployment needs an external system, that seam is called out explicitly rather than smuggled in through a default.

It is written for a working developer who wants the whole shape of a real tool in one readable pass rather than a tour of a framework. Each phase states the decision it makes and why, then shows the code that encodes it, so the reader can stop after any phase with something that runs and resume later without relearning the whole design. The prose is deliberately honest about trade-offs: where a simpler approach would break at scale, that ceiling is named instead of hidden behind a benchmark.

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.

Set up the workspace before writing any logic. The table below pins every dependency to a version so the behaviour you observe matches the tutorial; floating versions are the most common reason a reader’s output diverges from the text. Install exactly what the table lists, then confirm the toolchain reports the expected version before continuing.

Two configuration choices deserve attention up front. First, the project keeps its runtime entry and its test entry as separate scripts so that running tests never starts a server or writes to a data directory. Second, all tunables are read from one place — a small config module or environment variables — so that nothing depends on the working directory a command happens to be launched from.

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.

The first hard decision is where the boundary between parsing and doing sits. Input arrives as raw text — argv, environment variables, a file on disk — and this phase converts it exactly once into a typed object that the rest of the program trusts. Confining that conversion to a single module means every later layer receives clean, already-validated input and never re-checks a string, which removes a whole class of bugs where two modules quietly disagree about what a flag or a field means. The second decision is failure visibility: invalid input must produce an actionable message and a non-zero exit rather than a stack trace surfacing from three layers down. Getting these two boundaries right early is what lets the remaining phases stay small.

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.

This phase defines the data model that every other module speaks. The choice of shape matters more than it looks: flat records are easy to serialize and diff, nested structures model relationships but complicate equality checks, and identifiers must be stable across edits so that references never silently rebind. The code here stays pure — functions take data and return data, with no clocks, no disk, and no printing — because pure functions are the only kind that can be tested exhaustively without a fixture harness. When the model is right the surrounding code almost writes itself; when it is wrong every later phase pays interest.

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.

The core operation is where the project delivers its value, and the temptation is to cram every option into one function. Resist it. The main path should read as a short, obvious sequence — load, transform, emit — with the branching behaviour factored into small decisions that can be tested on their own. This phase also fixes the error contract: which failures are fatal, which are recoverable, and how a partial result is reported. A tool that can explain what it did and why it stopped is far easier to trust in a pipeline than one that only signals success or silence.

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.

Integration is where the project stops being a toy. Input may arrive in a format an external system produced, output may need to match a contract another system consumes, and the two rarely line up without adjustment. This phase owns the adapters — the small translation functions between the outside world’s shape and the internal model — and it owns the boundary decisions about what to do when the two disagree: coerce, reject, or warn and continue. Keeping adapters thin and explicit means a change to an external format touches one file, and the internal model stays stable as the ecosystem around it moves.

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.

The user-facing surface determines whether the project feels finished. A command-line tool owes its caller predictable stdout, meaningful stderr, and honest exit codes; a service owes a stable request and response schema plus consistent status handling. This phase wires the internal modules to that surface and nothing else — it contains no business logic of its own, only translation between the outside contract and the internal calls. That separation is what lets the same core serve a CLI today and an HTTP endpoint tomorrow without duplication, and it is why the tests for this layer assert process-level behaviour rather than poking at internals.

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.

The final phase turns a working program into a dependable one. Tests are the visible part, but the discipline behind them is deeper: every claim the earlier phases made is pinned by an executable check, and every failure mode the tutorial mentioned has a test that reproduces it before the fix. Edge cases — empty input, malformed records, concurrent invocations, interrupted writes — are enumerated and asserted rather than assumed away. The payoff is a suite that fails loudly and precisely when someone changes a decision, which is exactly the signal a maintainer wants the moment they touch the code.

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.

Design trade-offs

Minimal dependencies over framework convenience. A framework would hand over plumbing for free, but it would also own the interesting decisions this project exists to teach. Keeping the dependency surface small means the lifecycle is visible end to end, the install is instant, and the tool runs anywhere the stated runtime does. The cost is owning the edge cases yourself — which is precisely why each of them gets a test.

Explicit contracts over clever conventions. Where a convention would infer behaviour from a filename or a folder, the project asks for a named export or a declared field instead. It reads as slightly more verbose and is far easier to review: a reader sees the intent on the line that owns it rather than reconstructing it from directory layout. Debugging also gets cheaper, because the failure points at the declaration instead of the convention that silently produced it.

Deterministic behaviour over convenience defaults. Anything that could vary between machines — time, ordering, encoding, locale — is injected or pinned rather than read from the ambient environment. That choice costs a little ceremony and buys reproducible output, which is the property that makes the output diffable in review and the tests trustworthy across the team’s machines.

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.

Tests are organised by layer so a failure points at the decision that broke. Pure unit tests cover the transformation logic without touching disk or network and run in milliseconds; integration tests exercise the real entry point against a temporary working directory and assert the observable contract; a small end-to-end tier proves the whole path produces the documented output. Keeping the fast tiers large and the slow tier thin is what lets the suite run on every save while still catching integration mistakes.

Every test asserts a specific promise from the phases above rather than merely covering lines. A passing suite therefore means the tool kept its word: filters compose, identifiers stay stable, failures exit non-zero with a readable message, and the output matches the format a downstream consumer expects. When someone changes a contract the matching test fails with an exact diff, turning a silent regression into a line in the pull request.

Running the suite in CI is the last line of defence, but the same command runs locally before every commit, which is what keeps the feedback loop short. A green run means the documented behaviour still holds; a red run names the exact promise that broke. Treat the suite as executable documentation and it stays current, because a stale assertion fails the moment the code and the text disagree.

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.

The structure leaves obvious seams for growth. Each capability that could be added — a new output format, an extra filter, an interactive mode — lands in one layer because the boundaries between parsing, logic, and presentation are already drawn. Extensions that would break the current design are equally visible: the moment a feature needs cross-process coordination or a database, the storage interface is where the change belongs, and its tests tell you immediately whether the surrounding code survives the swap.