LLM engineering · Easy · 10 min

Prompt templates without surprises

Fill {{variables}} in a prompt, fail when one is missing, and keep user text from opening or closing template markers.

Write fillTemplate(template, vars). Each {{name}} (with optional spaces, like {{ name }}) is replaced by String(vars.name). If a template variable does not exist in vars, throw an error whose message includes its name. Note: 0 and '' are valid values.

The values come from the user, so remove the sequences {{ and }} from them before inserting. Do a single pass: inserted text is never read as template again.

TEMPLATE and INPUT are already defined.

Challenges 0/4

  • Fills every variable, spaces included
  • Replaces a repeated variable and accepts 0
  • Throws an error naming the missing variable
  • Neutralises {{ and }} in values and does not re-read them

function fillTemplate(template, vars) {
  // replace each {{ name }}; throw if a name is missing; strip {{ and }} from values
  let out = template;
  for (const [key, value] of Object.entries(vars)) {
    out = out.replace('{{' + key + '}}', value);
  }
  return out;
}

console.log(fillTemplate(TEMPLATE, INPUT));

Tab indents, Ctrl+Z undoes. To leave the editor with the keyboard: Esc, then Tab.

Console output appears here (console.log).

Why this matters

As soon as a prompt carries data from a form, an email or a document, you have a template. Both failures in this exercise are real: a missing variable that goes out as literal text without anyone noticing, and a user who types double braces and slips in a marker of their own. The second is the first step of a prompt injection. A template that fails early and treats outside text as data avoids both. To write the prompt that goes inside it, use our prompt writer.

Go deeper: the related tool →

This in production, with your data? Let's talk for 15 minutes →