Javascript Template Literals

A quick dive into Javascript template literals!
Javascript Template Literals
Template literals are string literals allowing embedded expressions.
You can use multi-line strings and string interpolation features (Expression & variable input) with them.
These were called ‘Template Strings’ in prior editions of the ES2015 sepcification.
Table of Contents
Syntax
|
Description
Template literals use the Backtick (``
) character to enclose them instead of double or single quotes ""
or ''
.
They can contain placeholders. These are denoted by a dollar sign and curly braces ${expression}
. The expression in the placeholder and the text between the backticks get passed to a function.
|
The default function just concatenates the parts into a single string.
If there is a preceeding expression (Tag); which is called a tagged template, the tag expression (normally a function) gets called with the trailing template literal.
|
To escape a backtick in a template literal, put a backslash (\
) before the backtick.
|
Multiline strings
Examples of using Template Literals with multi-line strings.
|
|
Expression Interpolation
To embed expressions within normal strings, you would use the following syntax:
|
The same example with Template literals:
|
Nesting Templates
In some cases Nesting templates is the easiest way to have configurable strings.
Using this example in ES5:
|
In ES2015 with nested template literals:
|
Tagged Templates
A more advanced form of template literals are tagged templates.
Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.
The name of the function used for the tag can be whatever you want.
Here is an example of using a Tagged Template:
|
Raw strings
The special raw property, available on the first argument to the tag function, allows you to access the raw strings as they were entered, without processing escape sequences.
|
In addition, the String.raw() method exists to create raw strings, just like the default template function and string concatenation would create.
|