Published: 2017-12-27
Updated: 2017-12-29
Web: http://fritzthecat-blog.blogspot.com/2017/12/es6-template-literals.html
The vision of building HTML components using just ES6 becomes realistic with Template Literals. They provide a templating mechanism that is built into browsers.
An ES6 template literal is text enclosed in `backticks`, possibly spanning several lines,
containing placeholders given by the popular ${expression}
syntax (→ interpolation expressions).
Template literals can contain other template literals.
ES6 defines template literals and tagged template literals.
Here is an example template literal, alerting "Hello Dolly":
const world = "Dolly" const output = `Hello ${world}` alert(output)
And here is an example for a tagged template literal (the tag-function not yet implemented, thus it would show nothing):
function formatHelloWorld(textPartsArray, ...parameters) { let resultText = "" // process input to resultText return resultText } const world = "Dolly" const output = formatHelloWorld `Hello ${world}` alert(output)
The formatHelloWorld
tag-function actually gets called when executing this source,
although there are no invocation-parentheses.
It receives a parsed representation of the template literal behind it,
including placeholder values, and it must output text.
There can be optional spaces between the function-name and the first backtick, even newlines,
but mostly the literal is directly appended to the name: formatHelloWorld`Hello ${world}`
Here are some explanations about template literals from the web:
Study the "Template Function" example to find out how powerful this concept is when combined with arrow-functions!
Click onto one of the buttons to get an example script into the text area. Below the script you find an explanation.
Reminiscences to the UNIX shell `command substitution` come up. But template literals are different, especially the tagged ones. Nevertheless both do the same: embedding the result of an expression into text. The aim of template literals is most likely to embed data-contents into HTML-layout, preparing for building web components via ES6.
Template literals start and end with ` (backtick).
If there is a backtick inside, it must be escaped by \ (backslash).
Template literals can span multiple lines, all kinds of whitespace inside will be preserved.
Interpolated expressions, like ${expression}
, will be substituted as soon as the
code is executed where the template literal resides.
This example shows several techniques.
Data can be referenced via complex expressions like ${persons[0].name}
.
The special character '$
' doesn't need to be escaped as long as it is not '${
'.
Due to preservation of spaces you can not indent source text inside backticks
(unless spaces don't matter in the result text).
Tagged template literals are preceded by a function name.
The backtick-literal will be passed to the function in a parsed state,
having evaluated all contained interpolation expressions.
This example shows how a tag function can be implemented.
It receives, as first parameter, an array of those text parts that are outside interpolation expressions,
and, as rest-parameter, all interpolation expressions, already replaced by actual values.
The tagFunction
example implementation wraps all rest-parameters into HTML <b> tags.
Mind that the ${money}
text-part must be escaped by backslash
to avoid its interpretation as interpolation expression.
This example shows how powerful template literals could be used for building HTML components.
An array of objects gets converted into a HTML table containing the property values of the objects.
To achieve this, arrow-functions are declared that evaluate to template literals that can contain other template literal functions.
Calling the template literal function finally with actual data gives a fully substituted HTML-text
that can be used to as innerHTML
of an element.
Special characters inside substituted data will be interpreted as HTML control-characters by the browser,
e.g. <, > or &, and thus must be escaped.
This example uses the tag-function html()
to escape substituted interpolation expressions,
e.g. contained in the test-string "'James' <Bond> & Co."
.
Further it facilitates the usage of unescaped backslashes inside the template literal,
to be seen as <i>\Company\</i>
.
The tag-function does this by using textParts.raw
, which delivers uninterpreted text fragments.
The textParts
parameter is a special array that provides that raw
property.
Why does the expected
text contain double backslashes around "Company"?
Because the default tag function, applied when no explicit tag-function was given,
does not use textParts.raw
, it interprets all backslashes,
so we must escape them.
This example shows that you can do a lot inside an interpolated expression. Here two functions are called, and their return is built together to a string representing first and last name of a person.
ɔ⃝ Fritz Ritzberger, 2017-12-27