Template literals

Defination

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 specification.

Syntax

1
`string text`
2
3
`string text line 1
4
string text line 2`
5
6
`string text ${expression} string text`
7
8
tag `string text ${expression} string text`
Copied!

Examples

1
console.log(`string text line 1
2
string text line 2`);
3
// "string text line 1
4
// string text line 2"
5
var a = 5;
6
var b = 10;
7
console.log(`Fifteen is ${a + b} and
8
not ${2 * a + b}.`);
9
// "Fifteen is 15 and
10
// not 20."
Copied!

Usage

Example from react-router.
1
const Topics = ({ match }) => (
2
<div>
3
<h2>Topics</h2>
4
<ul>
5
<li>
6
<Link to={`${match.url}/rendering`}>
7
Rendering with React
8
</Link>
9
</li>
10
<li>
11
<Link to={`${match.url}/components`}>
12
Components
13
</Link>
14
</li>
15
<li>
16
<Link to={`${match.url}/props-v-state`}>
17
Props v. State
18
</Link>
19
</li>
20
</ul>
21
22
<Route path={`${match.url}/:topicId`} component={Topic}/>
23
<Route exact path={match.url} render={() => (
24
<h3>Please select a topic.</h3>
25
)}/>
26
</div>
27
)
Copied!

References