Template EngineLoading saved progress…

Template Engine

Implement templateEngine(template, data) — take a string with {{ }} placeholders and return a copy where every placeholder has been swapped for a value from data. This is the core of Mustache-style templating: templateEngine('Hi {{name}}', { name: 'Ada' }) produces 'Hi Ada'. A placeholder holds a path{{ user.name }} reads data.user.name — and resolving that nested path against the data object is the heart of the problem. Text outside the braces is copied through exactly as-is.

Signature

// template: string  — text with zero or more {{ path }} placeholders.
// data:     object   — the values to substitute in.
//   A `path` is dot-separated: 'user.name' reads data.user.name.
// returns:  string   — the template with every {{ path }} replaced by its value.
//   A path that resolves to nothing renders as '' (empty string).
//   A non-string value is coerced: 0 → '0', false → 'false'.
function templateEngine(template, data): string;

Examples

// A single placeholder, looked up by name.
templateEngine('Hello, {{name}}!', { name: 'Ada' });
// → 'Hello, Ada!'
// A dot-path reads into a nested object.
templateEngine('Welcome back, {{user.name}}.', { user: { name: 'Grace' } });
// → 'Welcome back, Grace.'
// Whitespace inside the braces is ignored; a missing key renders empty.
templateEngine('{{ a }} and {{ b }}', { a: 'x' });
// → 'x and '

Notes

  • A path is a dot-path. {{ user.name }} means "read data.user.name." Split the captured path on . and walk into the object one segment at a time. Single names like {{ name }} are just a one-segment path.
  • Whitespace inside the braces does not matter. {{name}}, {{ name }}, and {{ name }} all refer to the same path. Trim it before you look it up.
  • A missing path renders as an empty string. If the key — or any parent on the path — is absent, substitute ''. Reading a missing nested path must not throw: {{ user.name }} against {} is '', not an error.
  • Coerce non-string values, and mind the falsy trap. A number, boolean, or other value becomes its string form. A value of 0 renders '0' and false renders 'false' — so the "is it missing?" test must distinguish absent from falsy. Do not drop 0 or false.
  • Literal text passes through untouched. Everything outside {{ }} is copied verbatim, including a template with no placeholders at all.
  • Scope: base interpolation only. No conditionals ({{#if}}), loops ({{#each}}), or partials — just {{ path }} substitution. Those extensions are noted at the end of the solution.
Loading editor…