Tagged Template Literals
A template literal is a string written in backticks. It can hold expressions inside ${} and can run over several lines. A tagged template puts a function name in front of the backticks, so that the function receives the pieces of the template and decides what the result is.
Template literals
Section titled “Template literals”Any expression can go inside ${}, and its value is converted to a string. A line break inside the backticks stays in the string.
const item = 'notebook';const price = 3.5;const quantity = 4;
console.log(`${quantity} x ${item} costs £${(price * quantity).toFixed(2)}`);console.log(`Line oneLine two`);This prints:
4 x notebook costs £14.00Line oneLine twoString.raw
Section titled “String.raw”Escape sequences such as \t (tab) and \n (new line) work in template literals as they do in quoted strings. String.raw is a built-in tag that keeps the backslashes as typed, while still filling in the ${} expressions. It is useful for Windows paths and for regular expression source.
const name = 'notes';
console.log(`Tab:\tdone`);console.log(String.raw`Tab:\tdone`);console.log(String.raw`C:\temp\new ${name}.txt`);This prints:
Tab: doneTab:\tdoneC:\temp\new notes.txtWriting a tag function
Section titled “Writing a tag function”A tag function is called with an array of the literal text pieces first, followed by the value of each ${} expression as a separate argument. A rest parameter gathers the values into an array.
function inspect(strings, ...values) { console.log(strings); console.log(values);}
const city = 'York';const temperature = 14;inspect`It is ${temperature}°C in ${city} today.`;This prints:
[ 'It is ', '°C in ', ' today.' ][ 14, 'York' ]There is always one more text piece than there are values, because the template starts and ends with text, even when that text is empty. The tag is called without parentheses, and whatever it returns becomes the value of the whole expression.
A practical tag: escaping HTML
Section titled “A practical tag: escaping HTML”Building HTML from user input is risky, because the input might contain markup. A tag can escape every value while leaving the template’s own markup alone.
const entities = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };const escapeHtml = (value) => String(value).replace(/[&<>"']/g, (ch) => entities[ch]);
function html(strings, ...values) { let result = strings[0]; values.forEach((value, i) => { result += escapeHtml(value) + strings[i + 1]; }); return result;}
const author = 'Sam';const comment = '<b>Great</b> & "cheap"';console.log(html`<p>${author} wrote: ${comment}</p>`);This prints:
<p>Sam wrote: <b>Great</b> & "cheap"</p>The <p> tags belong to the template, so they pass through unchanged, while the markup in comment is escaped. A tag does not have to return a string at all, which is how libraries use tags to build DOM nodes, SQL queries with bound parameters, or styled components.
Cooked and raw text
Section titled “Cooked and raw text”The strings array has a raw property, which holds the same text pieces with their escape sequences left as typed. String.raw is built on this property.
function show(strings) { console.log(strings[0]); console.log(strings.raw[0]);}
show`a\tb`;This prints:
a ba\tbSince ES2018, a tagged template may contain a backslash sequence that is not a valid escape, such as \unicode. The cooked entry for that piece is then undefined, and the raw entry still holds the text. An untagged template literal with the same text is a syntax error.
MDN describes the details on its template literals page.
Steve Griffith covers this topic in his video Tagged Template Literals.