Before we dig into the two features template literal and tagged template, let’s first examine the multiple meanings of the term template.
The following three things are significantly different, despite all having template in their names and despite all of them looking similar:
A web template is a function from data to text. It is frequently used in web development and often defined via text files. For example, the following text defines a template for the library Handlebars:
A template literal is a string literal with more features. For example, interpolation. It is delimited by backticks:
A tagged template is a function followed by a template literal. It results in that function being called and the contents of the template literal being fed into it as parameters.
getArgs() receives both the text of the literal and the data interpolated via
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
Second, template literals can span multiple lines:
Template literals always produce strings.
The expression in line A is a tagged template:
The last line is equivalent to:
The parameters of
['Hello ', ' ', '!']
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):
\tbecomes a tab
\\becomes a single backslash
\tbecomes a slash followed by a
\\becomes two backslashes
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.
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.
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
The library graphql-tag lets you create GraphQL queries via tagged templates:
Additionally, there are plugins for pre-compiling such queries in Babel, TypeScript, etc.
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.):
One example where that helps is strings with regular expressions:
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:
All remaining sections are advanced
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.
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.
There are two ways to fix this: via a tagged template or by trimming the result of the template literal.
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:
This time, the output is not indented:
The second fix is quicker, but also dirtier:
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):
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:
As a more complex example, we’d like to take an Array of addresses and produce an HTML table. This is the Array:
tmpl() that produces the HTML table looks as follows.
tmpl() takes the following steps:
<table>is produced via a nested templating function for single addresses (line 4). Note how it uses the string method
.trim()at the end, to remove unnecessary whitespace.
addrsvia the Array method
escapeHtml()is used to escape special HTML characters (line 6 and line 7). Its implementation is shown in the next section.
This is how to call
tmpl() with the addresses and log the result:
The output is:
Exercise: HTML templating
Exercise with bonus challenge: