← All Exercises
Mini Mustache Template Renderer
intermediatejavascript
Background
Mustache logic-less templates separate view from presentation, and the escaping rules are the security boundary that keeps user data out of the markup context.
Problem
Render templates supporting: {{name}} variables HTML-escaped by escaping ampersand, angle brackets, quotes, and apostrophes; {{{raw}}} variables inserted unescaped; {{#key}}body{{/key}} sections that render the body once when the value is truthy or once per element with {{.}} bound to the item when the value is an array, and render nothing otherwise. Output the rendered string.
Input
A JSON object {"template": string, "data": object} where sections do not nest.Output
A JSON object {"rendered": string}.Sample tests
Sample 1
Input: {"template":"Hello {{name}}! {{#vip}}[VIP] {{/vip}}Items: {{#items}}{{.}}, {{/items}}{{{raw}}}","data":{"name":"<Amy>","vip":true,"items":["a","b"],"raw":"<b>ok</b>"}}Expected: {"rendered":"Hello <Amy>! [VIP] Items: a, b, <b>ok</b>"}Sample 2
Input: {"template":"{{#disabled}}OFF{{/disabled}}missing: {{missing}}","data":{"disabled":false}}Expected: {"rendered":"missing: "}Your solution
Learning objective
Build a small template engine with correct escaping order and section semantics.