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));Console output appears here (console.log).
Go deeper: the related tool →
This in production, with your data? Let's talk for 15 minutes →