Implement a Template Engine From Scratch in JavaScript
Build a template engine from scratch in JavaScript with placeholders, nested paths, HTML escaping, loops and conditions, and no eval. Node.js 24.

A template engine turns a string with holes into a string with values. The one-line version, a replace with a regular expression, is a fair first answer. The conversation that follows is the real question: what about nested values like user.name, what about HTML in the data, what about loops and conditions and what must never happen when the template or the data is untrusted. This post builds a small engine on Node.js 24 in stages, escapes output by default, adds if and each blocks with a tiny parser and explains why none of it needs eval or new Function. For the security side of dynamic code, see using the Function constructor safely, or not at all.
The contract
render(template, data) returns a string. A placeholder is written {{ path }}, where path is a dotted lookup into data. Output is HTML-escaped unless the author opts out. A missing value renders as an empty string, not as the text undefined. Later we add {{#if path}}...{{/if}} and {{#each path}}...{{/each}}.
Version one: replace
function render(template, data) {
return template.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (match, path) => {
const value = path.split(".").reduce((obj, key) => obj?.[key], data);
return value ?? "";
});
}
const out = render("Hello {{ user.name }}, you have {{count}} messages.", {
user: { name: "Ada" },
count: 3,
});
console.log(out);Hello Ada, you have 3 messages.The regular expression captures a path of word characters and dots between double braces, with optional spaces. replace accepts a function, which receives the whole match and the capture. The lookup walks the path with reduce, and the optional chain obj?.[key] makes a missing intermediate object produce undefined instead of a TypeError. The ?? "" turns both undefined and null into an empty string, while keeping 0 and false, which || would wrongly erase.
Check that last claim.
console.log(render("[{{ n }}] [{{ flag }}] [{{ missing }}]", { n: 0, flag: false }));[0] [false] []Zero and false survive, and the missing key becomes empty.
Escaping by default
The version above is an injection hole the moment the template produces HTML. If a user's name is <script>alert(1)</script>, the result contains a live script tag. Escape the five characters that matter in HTML text and attribute values.
const escapes = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, (char) => escapes[char]);
}
function lookup(data, path) {
return path.split(".").reduce((obj, key) => obj?.[key], data);
}
function render(template, data) {
return template.replace(/\{\{\{\s*([\w.]+)\s*\}\}\}|\{\{\s*([\w.]+)\s*\}\}/g, (m, raw, escaped) => {
const value = lookup(data, raw ?? escaped) ?? "";
return raw !== undefined ? String(value) : escapeHtml(value);
});
}
console.log(render("<p>{{ bio }}</p>", { bio: '<b onclick="x()">hi</b>' }));
console.log(render("<p>{{{ bio }}}</p>", { bio: "<b>hi</b>" }));<p><b onclick="x()">hi</b></p>
<p><b>hi</b></p>Two syntaxes, as in Mustache and Handlebars: double braces escape, triple braces insert raw HTML for values the author trusts. The alternation lists the triple form first, because otherwise the double-brace pattern would match the inner two braces of a triple one. Making escaping the default is the design decision to defend: forgetting to escape is the common mistake, so the safe path is the one that needs no extra typing. The & must be escaped as well, or < in the data would round-trip to <.
Where the value lands matters. This escaping is correct for HTML text and quoted attributes. It is not correct inside a <script> block, in a URL, or in a CSS value, each of which has its own rules. Say that, because "I escape HTML" is not "I am safe in every context".
Conditions and loops
For blocks, a regular expression is the wrong tool, since blocks nest. Parse the template into a tree of nodes, then render the tree. Tokenize first.
function tokenize(template) {
const tokens = [];
const pattern = /\{\{\{?\s*([#/]?)([\w.]*)\s*([\w.]*)\s*\}?\}\}/g;
let last = 0;
let match;
while ((match = pattern.exec(template)) !== null) {
if (match.index > last) {
tokens.push({ type: "text", value: template.slice(last, match.index) });
}
const [whole, sigil, word, arg] = match;
const raw = whole.startsWith("{{{");
if (sigil === "#") tokens.push({ type: "open", name: word, path: arg });
else if (sigil === "/") tokens.push({ type: "close", name: word });
else tokens.push({ type: "var", path: word, raw });
last = pattern.lastIndex;
}
if (last < template.length) {
tokens.push({ type: "text", value: template.slice(last) });
}
return tokens;
}
console.log(tokenize("A{{#if ok}}B{{/if}}"));[
{ type: 'text', value: 'A' },
{ type: 'open', name: 'if', path: 'ok' },
{ type: 'text', value: 'B' },
{ type: 'close', name: 'if' }
]The tokenizer cuts the string into text, variables and block markers and does no interpretation. The parser then builds a tree from the tokens with a stack.
function parse(tokens) {
const root = { children: [] };
const stack = [root];
for (const token of tokens) {
const top = stack[stack.length - 1];
if (token.type === "open") {
const node = { type: token.name, path: token.path, children: [] };
top.children.push(node);
stack.push(node);
} else if (token.type === "close") {
const node = stack.pop();
if (stack.length === 0 || node.type !== token.name) {
throw new SyntaxError(`unexpected {{/${token.name}}}`);
}
} else {
top.children.push(token);
}
}
if (stack.length !== 1) {
throw new SyntaxError(`unclosed {{#${stack[stack.length - 1].type}}}`);
}
return root;
}Every open pushes a node on the stack, so the next tokens become its children. Every close pops it, and the check that the names match catches {{#if}}...{{/each}}. An unclosed block leaves the stack taller than one at the end, which is the error the last line reports. Errors with a message that names the tag are far more useful than a template that silently renders wrong.
Now render the tree.
function renderNode(node, scope) {
return node.children
.map((child) => {
switch (child.type) {
case "text":
return child.value;
case "var": {
const value = lookup(scope, child.path) ?? "";
return child.raw ? String(value) : escapeHtml(value);
}
case "if":
return lookup(scope, child.path) ? renderNode(child, scope) : "";
case "each": {
const items = lookup(scope, child.path) ?? [];
return items.map((item, index) => renderNode(child, { ...scope, this: item, index })).join("");
}
default:
return "";
}
})
.join("");
}
function render(template, data) {
return renderNode(parse(tokenize(template)), data);
}
const template = [
"{{#if user}}Hi {{ user.name }}.{{/if}}",
"{{#each items}} [{{ index }}:{{ this }}]{{/each}}",
].join("\n");
console.log(render(template, { user: { name: "Ada" }, items: ["a", "b"] }));
console.log(JSON.stringify(render(template, { items: [] })));Hi Ada.
[0:a] [1:b]
"\n"The first call prints both lines. In the second call, user is absent, so the if renders nothing, and items is empty, so the each renders nothing, leaving only the newline between two empty strings, which JSON.stringify shows as "\n". Inside an each, a new scope adds this and index, copying the outer scope so the loop body can still read outer values. A property named this is legal in an object, so this works with the same dotted-path lookup.
Why no eval
Engines such as EJS compile a template into JavaScript source and run it with new Function. That is fast, because the template becomes a function once, and dangerous, because the template is now code with the full power of your process. If any part of a template, or the path inside a placeholder, comes from a user, it becomes remote code execution.
The engine here never evaluates anything. A path is a list of property names walked with ?., and the tree is interpreted by renderNode. The cost is speed: it re-walks the tree on every render. The usual middle path is to parse once and cache the tree, as the next section shows.
One more guard belongs in lookup. Paths such as constructor.prototype or __proto__ read inherited members. Reading is mostly harmless, but exposing constructor lets a template reach Function. Restrict the walk to own properties.
function lookup(data, path) {
return path.split(".").reduce((obj, key) => {
if (obj == null) return undefined;
return Object.hasOwn(Object(obj), key) ? obj[key] : undefined;
}, data);
}
console.log(render("{{ constructor }}|{{ a.b }}", { a: { b: "ok" } }));|okconstructor is inherited, not an own property, so it renders as empty.
Compiling once
Parsing on every call is wasteful for a template rendered thousands of times. Split the work: compile(template) returns a function that holds the parsed tree.
function compile(template) {
const tree = parse(tokenize(template));
return (data) => renderNode(tree, data);
}
const greet = compile("Hello {{ name }}!");
console.log(greet({ name: "Ada" }), greet({ name: "<Linus>" }));Hello Ada! Hello <Linus>!The parse cost is paid once, and each render is a walk over a small tree. Template syntax errors now surface at compile time, which is when you want them.
Limits worth stating
Loops need a bound. A template that renders {{#each items}} over a list a user controls can be made to produce an enormous string, so a real engine caps the number of iterations or the output size and fails with a clear error instead of exhausting memory. The same goes for nesting depth: a deeply nested template can overflow the recursion in renderNode, and an input of a few thousand unclosed blocks is enough to try.
Whitespace is the other thing people notice first. The engine above keeps every character outside the braces, so a block tag on its own line leaves a blank line behind. Mustache solves this with "standalone" tag rules that remove a line containing only a block tag. It is a short addition to the tokenizer and a good follow-up to offer, because it shows you have read real output and not just written the engine.
Testing it
import test from "node:test";
import assert from "node:assert/strict";
test("escapes by default and allows raw", () => {
assert.equal(render("{{ x }}", { x: "<" }), "<");
assert.equal(render("{{{ x }}}", { x: "<" }), "<");
});
test("reports an unclosed block", () => {
assert.throws(() => render("{{#if a}}x", {}), SyntaxError);
});
test("loops over items with this and index", () => {
assert.equal(render("{{#each xs}}{{ index }}{{ this }}{{/each}}", { xs: ["a", "b"] }), "0a1b");
});ℹ tests 3
ℹ pass 3
ℹ fail 0

