Tagged templates allow our beloved template literals to be taken to a whole new level.
The typical use of a template literal is below -
let x = 1;
let y = 5;
console.log(`x is ${x}, y is ${y}`);
// x is 1, y is 5
Template literals allow us to avoid stupid statements like this -
console.log("x is " + x + ", y is " + y);
// x is 1, y is 5
Template literals are cool.
Tagged templates take the above function in a different way -
let x = 1;
let y = 5;
sum`x is ${x} y is ${y}`;
function sum(str, ...values) {
console.log(str, values);
// [ 'x is ', 'y is ', '' ] [ 1, 5 ]
}
The above code ’tags’ a template literal x is ${x} y is ${y} with sum.
Sum is also typically a function, which will have two arguments -
- plain text in the template literal
- values supplied in the template literal
Tagged templates are just plain functions masquerading for specific use cases. The above tagged template can be represented as -
// code, code and code
function sum([str1, str2], [value1, value2]) {
// more code
}
I have not used tagged templates that much, but they should be super useful when -
- reformatting strings/ user input
- trying to dissemble & reassemble part or whole of template literals (e.g see es2015-i18n-tag - translate literal strings and seamlessly use them with specified values)
- styling components (see styled components! )