Render mustache templates with HTML escaping and raw tags
An email service renders HTML messages from templates and user data. User data can contain characters like < and &, so by default every inserted value must be HTML-escaped. Trusted snippets, such as a pre-built signature, need a way to skip escaping.
Implement renderTemplate(template, data). It returns template with every tag replaced by a value looked up in data.
renderTemplate(template, data) // => string
{{ path }} inserts the value, HTML-escaped.{{{ path }}} inserts the value raw, with no escaping.{{name}} and {{ name }} are the same tag._ and $. Examples: name, user.address.city, items.0.title.{{ }}, {{ first name }}, {{ a..b }}, { name }, and an unclosed {{ name.data and read one segment at a time. Array indexes work as segments.toString or constructor count as missing. (Own properties of strings and arrays, such as length, are fine.)null or undefined, insert an empty string.String(value). So 0 becomes '0' and false becomes 'false'.Escaped tags replace these five characters:
& → &< → <> → >" → "' → 'Inserted values are final. If a value contains text like {{ name }}, it is not rendered again. The template text outside tags is never escaped.
const data = {
user: { first: 'Priya', company: 'Bolt & Nut <Ltd>' },
orders: [{ id: 'A-17', count: 0 }],
footer: '<em>Sent by Mailroom</em>',
};
renderTemplate('Hi {{ user.first }} from {{user.company}}!', data);
// => 'Hi Priya from Bolt & Nut <Ltd>!'
renderTemplate('Order {{ orders.0.id }}: {{ orders.0.count }} items', data);
// => 'Order A-17: 0 items'
renderTemplate('<p>{{{ footer }}}</p>', data);
// => '<p><em>Sent by Mailroom</em></p>'
renderTemplate('[{{ user.phone }}] [{{ missing.deep.path }}]', data);
// => '[] []'
renderTemplate('{{ first name }} and {{}}', data);
// => '{{ first name }} and {{}}'