Skip to content

Tagged Template

In one line

A tagged template applies a function (tag) to a template literal, receiving the string parts and interpolated values separately.

In simple words

A tagged template literal lets you prefix a template literal with a function (the tag). The function receives an array of the static string parts and the interpolated values as separate arguments, so it can process, transform, or escape them in any way.

The tag function signature is (strings, ...values) where strings is the literal text split at each ${} and values are the interpolated expressions. This enables safe HTML escaping, internationalization, SQL query building, syntax highlighting, and raw string access (via strings.raw).

Libraries like styled-components and graphql-tag use tagged templates to parse their DSLs. The tag can return anything — not just a string. It is a powerful but niche feature for building embedded domain-specific languages.

Example

javascript
function html(strings, ...values) {
  return strings.reduce((acc, str, i) => {
    const val = values[i] != null ? String(values[i]).replace(/</g, "&lt;") : "";
    return acc + str + val;
  }, "");
}

const userInput = "<script>alert(1)</script>";
const safe = html`<div>${userInput}</div>`;
console.log(safe);
// <div>&lt;script&gt;alert(1)&lt;/script&gt;</div>

The html tag escapes interpolated values to prevent XSS. strings holds the literal parts; values holds the interpolations.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary