Start with a regex replace: find {{ path }}, walk the path through the data, and print the value or nothing. The interview then adds what real template languages do: escape HTML by default (with {{{raw}}} as the explicit way out), {{#if}}…{{else}}…{{/if}} that nests, and loops. The strong answer stops using regex replacement for structure and compiles: tokenize the template once into a tree of text, value, if and each nodes, report malformed templates with their position, then render the tree against data with proper scopes (this, @index, outer fields). And it never turns template text into code with eval or new Function.
Write a templating engine that does variables substitution and simple conditionals.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
One replace with a callback: capture the path, walk it with reduce and stop safely on null/undefined, and print '' for missing values (but still print 0 and false). Text that isn't a tag passes through untouched.
// Replace {{ path }} with the value at that path ("user.name"); missing values print nothing.function render(template, data) {return template.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, path) => {const value = path.split('.').reduce((obj, key) => (obj == null ? undefined : obj[key]), data);return value == null ? '' : String(value);});}
passes 3 checks run on every build, against the native method where there is one
- replaces variables and nested paths
- missing values print nothing; 0 and false print
- text without tags is unchanged
Output goes into HTML, so values are escaped by default: &, <, >, " and '. Without that, a user's name of <script> is an XSS hole. {{{ }}} opts out for trusted HTML. Conditionals are resolved innermost first, by repeatedly matching an if block that contains no other if, which handles nesting without a parser. An empty array counts as false, the way Handlebars treats it.
const ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };const escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => ESCAPES[c]);const lookup = (data, path) => path.split('.').reduce((obj, key) => (obj == null ? undefined : obj[key]), data);// Like most template languages, an empty list counts as false.const truthy = (v) => (Array.isArray(v) ? v.length > 0 : Boolean(v));function render(template, data) {// Conditionals first, innermost first: a block with no {{#if}} inside it.const block = /\{\{#if\s+([\w.]+)\s*\}\}((?:(?!\{\{#if)[\s\S])*?)\{\{\/if\}\}/;let out = template;for (let m = block.exec(out); m; m = block.exec(out)) {const [whole, path, body] = m;const [yes, no = ''] = body.split(/\{\{else\}\}/);out = out.slice(0, m.index) + (truthy(lookup(data, path)) ? yes : no) + out.slice(m.index + whole.length);}return out.replace(/\{\{\{\s*([\w.]+)\s*\}\}\}/g, (_, path) => String(lookup(data, path) ?? '')) // {{{raw}}}.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, path) => escapeHtml(String(lookup(data, path) ?? ''))); // escaped by default}
passes 4 checks run on every build, against the native method where there is one
- values are HTML-escaped by default
- triple braces insert raw HTML
- if and else
- nested ifs
Regex replacement breaks down once blocks nest and loop. One pass with a tag regex produces tokens; a stack builds the tree (#if/#each push, /if//each pop, else switches the open block to its other branch), and anything unbalanced throws a SyntaxError with its position. Rendering walks the tree with a list of scopes: inside {{#each}}, this is the item, @index/@first/@last are loop variables, and other names fall back to outer scopes. The compiled function is reused for every render, and because the template is interpreted, not turned into JavaScript, no template can execute code.
const ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };const escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => ESCAPES[c]);const truthy = (v) => (Array.isArray(v) ? v.length > 0 : Boolean(v));// Compile once into a tree, render many times. No eval and no new Function: template text never// becomes code, so a template can't run anything.function compile(template) {const TAG = /\{\{\{\s*([\w.@]+)\s*\}\}\}|\{\{\s*(#if|#each|else|\/if|\/each)?\s*([\w.@]*)\s*\}\}/g;const root = { type: 'root', children: [] };const stack = [root];const top = () => stack[stack.length - 1];const into = () => (top().inElse ? top().otherwise : top().children);let last = 0;for (let m = TAG.exec(template); m; m = TAG.exec(template)) {if (m.index > last) into().push({ type: 'text', value: template.slice(last, m.index) });last = TAG.lastIndex;const [, raw, keyword, path] = m;if (raw) into().push({ type: 'value', path: raw, escape: false });else if (!keyword) {if (!path) throw new SyntaxError(`empty {{ }} at ${m.index}`);into().push({ type: 'value', path, escape: true });} else if (keyword === '#if' || keyword === '#each') {if (!path) throw new SyntaxError(`{{${keyword}}} needs a value at ${m.index}`);const node = { type: keyword.slice(1), path, children: [], otherwise: [], inElse: false, at: m.index };into().push(node);stack.push(node);} else if (keyword === 'else') {if (top().type === 'root' || top().inElse) throw new SyntaxError(`unexpected {{else}} at ${m.index}`);top().inElse = true;} else {const want = keyword.slice(1); // "/if" closes an ifif (top().type !== want) throw new SyntaxError(`unexpected {{${keyword}}} at ${m.index}`);stack.pop();}}if (stack.length > 1) throw new SyntaxError(`{{#${top().type} ${top().path}}} at ${top().at} is never closed`);if (last < template.length) root.children.push({ type: 'text', value: template.slice(last) });return (data) => renderAll(root.children, [{ value: data, vars: {} }]);}// Scopes from outer to inner. "this" is the innermost value, "@index" a loop variable, and a name// is looked up from the innermost scope outwards, so a loop body can still read outer fields.function lookup(path, scopes) {const inner = scopes[scopes.length - 1];if (path.startsWith('@')) return inner.vars[path];const [first, ...rest] = path.split('.');let base;if (first === 'this') base = inner.value;else {const scope = [...scopes].reverse().find((s) => s.value != null && typeof s.value === 'object' && first in s.value);base = scope?.value[first];}return rest.reduce((obj, key) => (obj == null ? undefined : obj[key]), base);}function renderAll(nodes, scopes) {let out = '';for (const node of nodes) {if (node.type === 'text') out += node.value;else if (node.type === 'value') {const v = lookup(node.path, scopes);const s = v == null ? '' : String(v);out += node.escape ? escapeHtml(s) : s;} else if (node.type === 'if') {out += renderAll(truthy(lookup(node.path, scopes)) ? node.children : node.otherwise, scopes);} else if (node.type === 'each') {const list = lookup(node.path, scopes);if (!Array.isArray(list) || list.length === 0) out += renderAll(node.otherwise, scopes);elselist.forEach((item, i) => {const vars = { '@index': i, '@first': i === 0, '@last': i === list.length - 1 };out += renderAll(node.children, [...scopes, { value: item, vars }]);});}}return out;}const render = (template, data) => compile(template)(data);
passes 6 checks run on every build, against the native method where there is one
- each, with this, @index and outer fields
- each over an empty list renders its else
- nested each sees both loops
- compile once, render many
- malformed templates throw a SyntaxError with the position
- a template can't run code
Escaping by default is the security feature
Mustache and Handlebars escape {{ }} and require triple braces for raw HTML; React escapes everything in JSX and makes raw HTML a deliberately awkward dangerouslySetInnerHTML. The safe path is the easy one, so XSS needs a visible opt-out.
Compile once
Template engines parse a template once and cache the compiled form, then render it per request or per email. Parsing on every render is the slow part.
Email and notification templates
Transactional emails ("Hi {{firstName}}, your order {{orderId}} shipped") are where these engines run every day, often with conditionals for optional sections and loops for line items.
Not escaping HTML: any user-controlled value becomes a script injection.
Building a function from the template with
new Functionor template literals: a template can then run arbitrary code.Printing
undefinedornullinstead of an empty string, or hiding0because it's falsy.A non-greedy regex for
{{#if}}…{{/if}}that pairs the outer opening tag with the inner closing tag.Silently ignoring an unclosed block instead of reporting where it starts.
How would you add helpers like {{uppercase name}}?
Allow a helper name before the path in the tag regex, look it up in a registry of functions, and call it with the resolved values. Keep helpers as plain functions so templates still can't run arbitrary code.
How do you escape for an attribute or a URL?
HTML-escaping covers element text and quoted attributes. A value going into href also needs its scheme checked (reject javascript:), and into a query string it needs encodeURIComponent; context-aware engines pick the escape by where the value lands.
What's the cost of rendering?
Compiling is O(n) in the template length; rendering is O(output size). Caching compiled templates by their source string removes the compile cost after the first render.
- mustache.github.io/mustache.5.html
- handlebarsjs.com/guide/expressions.html#html-escaping
- handlebarsjs.com/guide/builtin-helpers.html
- cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace