Template Literals are string literals which allow embedded expressions. Before ES6 introduced them, they were called as the Template Strings
ES6 template literals can handle following features easily :
- Multiline strings
- Basic String Formatting (String Interpolation) – Use variables as sub parts of the string
- HTML escaping – Safely insert string into a HTML by transforming it
`Hello this is how template strings are declared`
JavaScriptAgainst the standard ‘ and ” quotes template literals uses backticks `
It allows us to embed variables or expressions directly within them. They are enclosed in backticks “.
let name = 'Sujay';
let greeting = `Good morning ${name}`;
console.log(greeting); // Good morning Sujay
JavaScriptHere, Good morning ${name}
is a template literal and we have embedded the name variable directly within it.
We can also embed expressions or variables with the help of the ${...}
syntax
const a = 10;
const b = 12;
// embed expression within template literal
const result = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(result);
// The sum of 10 and 12 is 22.
JavaScriptTagged Templates
Tagged templates are an advanced form of template literals in Javascript. They allow you to parse template literals with a function.
Furthermore, you don’t need to use parentheses ()
when passing the template literal to the function. For example,
function greet(message) {
return message;
}
// create a tagged template
let result = greet`Hello Sujay`;
console.log(result); // [ 'Hello Sujay' ]
JavaScriptHere, unlike regular function arguments, the template literal is split into an array.
Multi-line Strings
Before ES6, we had to use escape characters for new line like:
// Traditional multi-line string
const poem = "Roses are red,\n Violets are blue, \n Sugar is sweet, \n And so are you.";
console.log(poem);
// Output
Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.
JavaScriptNow, we can create multi-line strings using Template Literals (with ES6)
// Multi-line string using temaplate literals
const poemTemplate = `
Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.
;
`
console.log(poemTemplate);
// Output
Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.
JavaScriptUsing single and double quotes
You can also use single and double quotes in a template literal without escaping:
let str = `What's up?`
JavaScriptTo escape a backtick in a template literal, use a backslash (\
) before the backtick:
let str = `A backtick (\`) can appear in a template literal`
console.log(str);
// A backtick ` can appear in a template literal
JavaScriptHTML templates
With the ability to create multi-line strings and dynamically substitute parts of a string with variables and expressions, template literals make it easy to use HTML templates in Javascript.
Let us say, that we get some data from an API that looks like the below :
const person = {
id: 1,
firstName: 'John',
lastName: 'Doe',
email: 'john.doe@gmail.com'
}
JavaScriptThe following example code returns an HTML template for the above person
object:
const createPersonMarkup = data => {
return `
<div class="card" id="${data.id}">
<div class="card-body">
<h3 class="card-title">${data.firstName} ${data.lastName} </h3>
<p class="text-muted"> ${data.email} </p>
</div>
</div>
}
JavaScriptThe above function will return the following HTML markup for the person
object we declared before:
<div class="card" id="1">
<div class="card-body">
<h3 class="card-title"> John Doe </h3>
<p class="text-muted"> john.doe@gmail.com</p>
</div>
</div>
JavaScriptComparing two arrays
The most magical usage of template literals is comparing two arrays of primitive values. Example, you can compare two array of strings like this
const a = ['one', 'two', 'three'];
const b = ['one', 'two', 'three'];
const equal = `${a}` === `${b}`;
JavaScriptIn the snippet above, we leverage the implicit conversion of Array.toString
method and then compare both results.
Very important to note, this works with primitive types only: numbers, strings and booleans;
When used with objects, this will fail because [Object object]
=== [Object object]
Pingback: Javascript - ES6 Features - xplor4r