Hiprup

What is a tagged template literal?

A tagged template lets a function process a template literal's strings and interpolated values.

  • How — write fn`text ${value}`; the function receives the string parts and the values separately.

  • Uses — escaping/sanitising input, internationalisation, and styling (e.g. styled-components).

Full control: transform a template before producing the final string.

// Tag function receives strings and values separately
function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => {
    return result + str + (values[i] !== undefined ? `<mark>${values[i]}</mark>` : '');
  }, '');
}

const name = 'John';
const age = 30;
const html = highlight`Hello, ${name}! You are ${age} years old.`;
// 'Hello, <mark>John</mark>! You are <mark>30</mark> years old.'

// HTML escaping tag
function safeHtml(strings, ...values) {
  const escape = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;');
  return strings.reduce((r, s, i) => r + s + (values[i] !== undefined ? escape(values[i]) : ''), '');
}

const userInput = '<script>alert(1)</script>';
const safe = safeHtml`<div>${userInput}</div>`;
// '<div>&lt;script&gt;alert(1)&lt;/script&gt;</div>' — XSS prevented!

// styled-components uses tagged templates
// const Button = styled.button`
//   color: ${props => props.primary ? 'blue' : 'gray'};
//   font-size: 16px;
// `;

The tag function receives strings (the literal parts) and values (the interpolated expressions) separately. highlight wraps values in <mark> tags. safeHtml escapes HTML in values (XSS prevention). styled-components uses this to define CSS with dynamic values. The tag function can return anything — not just a string.

Show the tag function receiving strings and values. The HTML sanitization example demonstrates practical XSS prevention.

Mention that styled-components, GraphQL (gql), and lit-html all use tagged templates. The tag can return any type (not just strings).

What is a tagged template literal? | Hiprup