JavaScript for impatient programmers (beta)
Please support this book: buy it or donate
(Ad, please don’t block.)

17. Using template literals and tagged templates

Before we dig into the two features template literal and tagged template, let’s first examine the multiple meanings of the term template.

17.1. Disambiguation: “template”

The following three things are significantly different, despite all having template in their names and despite all of them looking similar:

17.2. Template literals

Template literals have two main benefits, compared to normal string literals.

First, they support string interpolation: you can insert expressions if you put them inside ${ and }:

const MAX = 100;
function doSomeWork(x) {
  if (x > MAX) {
    throw new Error(`At most ${MAX} allowed: ${x}!`);
  }
  // ···
}
assert.throws(
  () => doSomeWork(101),
  {message: 'At most 100 allowed: 101!'});

Second, template literals can span multiple lines:

const str = `this is
a text with
multiple lines`;

Template literals always produce strings.

17.3. Tagged templates

The expression in line A is a tagged template:

const first = 'Lisa';
const last = 'Simpson';

const result = tagFunction`Hello ${first} ${last}!`; // A

The last line is equivalent to:

const result = tagFunction(['Hello ', ' ', '!'], first, last);

The parameters of tagFunction are:

The static (fixed) parts of the literal (the template strings) are separated from the dynamic parts (the substitutions).

tagFunction can return arbitrary values and gets two views of the template strings as input (only the cooked view is shown in the previous example):

The raw view enables raw string literals via String.raw (described later) and similar applications.

Tagged templates are great for supporting small embedded languages (so-called domain-specific languages). We’ll continue with a few examples.

17.3.1. Tag function library: lit-html

lit-html is a templating library that is based on tagged templates and used by the frontend framework Polymer:

import {html, render} from 'lit-html';

const template = (items) => html`
  <ul>
    ${
      repeat(items,
        (item) => item.id,
        (item, index) => html`<li>${index}. ${item.name}</li>`
      )
    }
  </ul>
`;

repeat() is a custom function for looping. Its 2nd parameter produces unique keys for the values returned by the 3rd parameter. Note the nested tagged template used by that parameter.

17.3.2. Tag function library: re-template-tag

re-template-tag is a simple library for composing regular expressions. Templates tagged with re produce regular expressions. The main benefit is that you can interpolate regular expressions and plain text via ${} (see RE_DATE):

import {re} from 're-template-tag';

const RE_YEAR = re`(?<year>[0-9]{4})`;
const RE_MONTH = re`(?<month>[0-9]{2})`;
const RE_DAY = re`(?<day>[0-9]{2})`;
const RE_DATE = re`/${RE_YEAR}-${RE_MONTH}-${RE_DAY}/u`;

const match = RE_DATE.exec('2017-01-27');
assert.equal(match.groups.year, '2017');

17.3.3. Tag function library: graphql-tag

The library graphql-tag lets you create GraphQL queries via tagged templates:

import gql from 'graphql-tag';

const query = gql`
  {
    user(id: 5) {
      firstName
      lastName
    }
  }
  `;

Additionally, there are plugins for pre-compiling such queries in Babel, TypeScript, etc.

17.4. Raw string literals

Raw string literals are implemented via the tag function String.raw. They are a string literal where backslashes don’t do anything special (such as escaping characters etc.):

assert.equal(String.raw`\back`, '\\back');

One example where that helps is strings with regular expressions:

const regex1 = /^\./;
const regex2 = new RegExp('^\\.');
const regex3 = new RegExp(String.raw`^\.`);

All three regular expressions are equivalent. You can see that with a string literal, you have to write the backslash twice to escape it for that literal. With a raw string literal, you don’t have to do that.

Another example where raw string literal are useful is Windows paths:

const WIN_PATH = String.raw`C:\foo\bar`;
assert.equal(WIN_PATH, 'C:\\foo\\bar');

17.5. (Advanced)

All remaining sections are advanced

17.6. Multi-line template literals and indentation

If you put multi-line text in template literals, two goals are in conflict: On one hand, the text should be indented to fit inside the source code. On the other hand, its lines should start in the leftmost column.

For example:

function div(text) {
  return `
    <div>
      ${text}
    </div>
  `;
}
console.log('Output:');
// Replace spaces with mid-dots:
console.log(div('Hello!').replace(/ /g, '·'));

Due to the indentation, the template literal fits well into the source code. Alas, the output is also indented. And we don’t want the return at the beginning and the return plus two spaces at the end.

Output:

····<div>
······Hello!
····</div>
··

There are two ways to fix this: via a tagged template or by trimming the result of the template literal.

17.6.1. Fix: template tag for dedenting

The first fix is to use a custom template tag that removes the unwanted whitespace. It uses the first line after the initial line break to determine in which column the text starts and cuts off the indents everywhere. It also removes the line break at the very beginning and the indentation at the very end. One such template tag is dedent by Desmond Brand:

import dedent from 'dedent';
function divDedented(text) {
  return dedent`
    <div>
      ${text}
    </div>
  `;
}
console.log('Output:');
console.log(divDedented('Hello!'));

This time, the output is not indented:

Output:
<div>
  Hello!
</div>

17.6.2. Fix: .trim()

The second fix is quicker, but also dirtier:

function divDedented(text) {
  return `
<div>
  ${text}
</div>
  `.trim();
}
console.log('Output:');
console.log(divDedented('Hello!'));

The string method .trim() removes the superfluous whitespace at the beginning and at the end, but the content itself must start in the leftmost column. The advantage of this solution is not needing a custom tag function. The downside is that it looks ugly.

The output looks like it did with dedent (however, there is no line break at the end):

Output:
<div>
  Hello!
</div>

17.7. Simple templating via template literals

While template literals look like web templates, it is not immediately obvious how to use them for (web) templating: A web template gets its data from an object, while a template literal gets its data from variables. The solution is to use a template literal in the body of a function whose parameter receives the templating data. For example:

const tmpl = (data) => `Hello ${data.name}!`;
assert.equal(tmpl({name: 'Jane'}), 'Hello Jane!');

17.7.1. A more complex example

As a more complex example, we’d like to take an Array of addresses and produce an HTML table. This is the Array:

const addresses = [
  { first: '<Jane>', last: 'Bond' },
  { first: 'Lars', last: '<Croft>' },
];

The function tmpl() that produces the HTML table looks as follows.

const tmpl = (addrs) => `
<table>
  ${addrs.map(
    (addr) => `
      <tr>
        <td>${escapeHtml(addr.first)}</td>
        <td>${escapeHtml(addr.last)}</td>
      </tr>
      `.trim()
  ).join('')}
</table>
`.trim();

tmpl() takes the following steps:

This is how to call tmpl() with the addresses and log the result:

console.log(tmpl(addresses));

The output is:

<table>
  <tr>
        <td>&lt;Jane&gt;</td>
        <td>Bond</td>
      </tr><tr>
        <td>Lars</td>
        <td>&lt;Croft&gt;</td>
      </tr>
</table>

17.7.2. Simple HTML-escaping

function escapeHtml(str) {
  return str
    .replace(/&/g, '&amp;') // first!
    .replace(/>/g, '&gt;')
    .replace(/</g, '&lt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;')
    .replace(/`/g, '&#96;')
    ;
}

  Exercise: HTML templating

Exercise with bonus challenge: exercises/template-literals/templating_test.js

17.8. Further reading

  Quiz

See quiz app.