How Do You Use Template Literals?
Problem
You want to know how to use a template literal in a project.
Solution
Template literals are very similar to template systems like
Handlebars
. Template literals give you the ability to set placeholders for values and render them at runtime.
The Code
var characterName = 'Pinky'
var quote = `Same thing we do every night ${characterName}!`;
console.log(quote) //Same thing we do every night Pinky!
Listing 14-1.
Using Template Literals
How It Works
Template literals work in a similar way to using a template system like Handlebars. Instead of using single or double quotes, template literals use
backticks
. This is similar to using quotes to work with a string; however, if you use single or double quotes you cannot add expressions to the template literal.
Expressions
are placeholders that will display a value when rendered. Expressions are defined by using a dollar sign and curly braces (${expression}). In Listing 14-1, there is a variable called
characterName
. When the variable quote is rendered to the browser, it will also display the value of characterName. If single or double quotes are used, then everything will be rendered as is, meaning that expressions will not be rendered. However, single and double quotes can be used inside template literals.
Can You Use Template Literals with Functions ?
Problem
You want to call a function that will work with a template literal.
Solution
These are called tagged template literals. With these, you can modify a template literal using a function.
The Code
function countdown(stringLiteralArray, ...values){
console.log(stringLiteralArray); //returns full array
console.log(stringLiteralArray[1]); //returns Mississippi
console.log(values); //returns array of values
console.log(values[0]); //returns 1
console.log(values[1]); //returns 2
let fullSentance = values[0] + stringLiteralArray[1] + values[1] + stringLiteralArray[2];
return fullSentance;
}
let one = 1;
let two = 2;
let results = countdown `${one} Mississippi ${two} Mississippi`;
console.log(results); //returns 1 Mississippi 2 Mississippi
Listing 14-2.
Using a Tagged Template Function
How It Works
Tagged template functions allow you to take a template literal and its values as its parmeters. The template literal comes over as an array, where each word is an element of that array. The values come over using ...rest by way of the spread operator. Passing values this way also gives you an array and avoids the arguments object. Inside the function’s body, the parameters can be arranged in any order you like and then returned to the caller.
Can You Create Line Breaks with Template Literals?
Problem
You want to have line breaks inside the generated string.
Solution
Line breaks can be created in a much more intuitive way than concatenating strings.
The Code
var seriesOfWords = ' this is line one
this is line two
this is line three';
console.log(seriesOfWords);
var temp = `
one
two
three
`
console.log(temp);
Listing 14-3.
Using Line Breaks with Template Literals
How It Works
When adding line breaks using strings, most of the time you use a linefeed character, by using the backward slash and n (as in
). The JavaScript engine will see it and render everything after that on the next line. Template literals give you a more natural way of handing this. It will render everything as it is represented in the backticks.
When using the
GeneratorFunction constructor
, you can pass parameters; however, these parameters must be a list of comma-separated strings. The last parameter defines what the function does.
How Do You Use the Raw Property with a Template Literal?
Problem
You want to know how to use the raw property when using a template literal in a function.
Solution
The raw property gives you raw strings as they are passed in to the function.
The Code
function rawWithVars(stringArray, ...values){
console.log(stringArray.raw)
console.log(stringArray.raw[2]) //returns Jones
console.log(stringArray[2]) //returns Jones
}
let name1 = 'Luke';
let name2 = 'Jessica';
let name3 = 'Danny';
let name4 = 'Matt';
rawWithVars `${name1} Cage
${name2} Jones
${name3} Rand
${name4} Murdock`;
Listing 14-4.
Returning a String with the Raw Property
How It Works
When using a tagged template function, the first parameter is the string that contains a raw property. Normally this property gives you an array of string literals. When using the raw property, you get an array with values exactly as they are in the template literal. In the example in Listing 14-4, a line break has been added to each name. When using the raw property, they are printed just as they were put into the template literal.
Can You Update Expressions Using a Function?
Problem
You have a template literal and want to update expressions dynamically.
Solution
Values returned from a function can be used in template literal expressions.
The Code
var str = `Today is ${getToday()}`;
function getToday(){
var myDate = new Date();
return myDate.getMonth() +'/' + myDate.getDate() + '/' + myDate.getFullYear();
}
console.log(str);
Listing 14-5.
Using a Function to Give Expressions Values
How It Works
Similar to using variables for expressions
, the value returned from a function can be used in a template literal. When the template literal is rendered, the function will execute and return the value. In Listing 14-5, the
getToday function
is called when rendering the str template. When rendered, the function is called. It fills the expression and prints the result.