Template Engine Implementation in JavaScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Template Engine runs in O(n) time and O(n) space, in JavaScript as in every other language.
- ✓There is no template engine in the language, but there is a compiler hook. A tagged template function receives `(strings, ...values)` where `strings` is a frozen array carrying a `.raw` companion, and the engine allocates that array once per call site and hands you the identical object on every later evaluation, which makes it a perfect `WeakMap` key.
- ✓Key the cache on the `strings` array itself rather than on `strings.join('\u0000')`. Identity is exact, the lookup is a pointer compare, and the entry dies with the module that owns the call site.
- ✓The JavaScript trap: The fast version of this compiles the plan to source text and calls `new Function(...)`. It stops working the moment anyone adds a Content-Security-Policy without `unsafe-eval`: `new Function` and `eval` are gated by the same check, the constructor throws an `EvalError`, and it throws on first render rather than at load, so it survives every test run served without CSP headers.
- ✓V8 does not materialise a new string per `+=`. It allocates a cons-string node and defers the copy until something reads the result flat, so an accumulating loop is cheap and the flatten cost lands on whoever consumes the output.
What Template Engine actually is
Template Engine in JavaScript: what you actually reach for
JavaScript implementation
// The frozen `strings` array is created once per call site and reused for every
// later evaluation, so it is a stable WeakMap key: one compile per site, ever.
const COMPILED = new WeakMap();
class SafeHtml {
constructor(text) { this.text = text; }
toString() { return this.text; }
}
const raw = (text) => new SafeHtml(String(text));
const ENTITY = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
const escape = (v) => String(v).replace(/[&<>"']/g, (c) => ENTITY[c]);
function compile(strings) {
const lits = Array.from(strings); // cooked text, not strings.raw
const holes = lits.length - 1;
// A closure tree, not new Function(...): codegen needs 'unsafe-eval' and dies
// under a strict Content-Security-Policy.
return (values) => {
let out = lits[0];
for (let i = 0; i < holes; i++) {
const v = values[i];
out += v instanceof SafeHtml ? v.text : escape(v);
out += lits[i + 1];
}
return out;
};
}
export function html(strings, ...values) {
let render = COMPILED.get(strings);
if (render === undefined) {
render = compile(strings);
COMPILED.set(strings, render); // GC'd with the call site's array
}
return new SafeHtml(render(values));
}
const row = (dep) => html`<td>${dep.platform}</td><td>${dep.note}</td><td>${raw(dep.badge)}</td>`;
console.log(String(row({ platform: "4B", note: 'delayed <20" min>', badge: "<em>live</em>" })));
console.log(String(row({ platform: "9", note: "on time", badge: "" })));Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Template Engine?
There is no template engine in the language, but there is a compiler hook. A tagged template function receives `(strings, ...values)` where `strings` is a frozen array carrying a `.raw` companion, and the engine allocates that array once per call site and hands you the identical object on every later evaluation, which makes it a perfect `WeakMap` key. `new Function` gives you real code generation. Nothing in the platform encodes HTML: `encodeURIComponent` is for URLs, and in a browser the only built-in encoder is round-tripping through `Node.textContent` and reading `innerHTML` back.
What is the most common JavaScript mistake when implementing Template Engine?
The fast version of this compiles the plan to source text and calls `new Function(...)`. It stops working the moment anyone adds a Content-Security-Policy without `unsafe-eval`: `new Function` and `eval` are gated by the same check, the constructor throws an `EvalError`, and it throws on first render rather than at load, so it survives every test run served without CSP headers. Worse, the browser reports it as a policy violation on the page, not a stack trace in your bundle. The closure tree below produces byte-identical output and never touches the evaluator.
How does Template Engine actually perform in JavaScript?
V8 does not materialise a new string per `+=`. It allocates a cons-string node and defers the copy until something reads the result flat, so an accumulating loop is cheap and the flatten cost lands on whoever consumes the output. The real hazard is the hole callback: if the compiled closure reads `data[key]` across objects with different hidden classes, the inline cache goes polymorphic, then megamorphic past four shapes, and each lookup degrades to a dictionary probe. Passing a positional values array, which a tagged template already does, keeps that site monomorphic forever. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialMost AI and dev tools have a student plan. See which ones and how to claim them on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.