Tagged templates allow our beloved template literals to be taken to a whole new level.
The typical use of a template literal is below -
|
|
Template literals allow us to avoid stupid statements like this -
|
|
Template literals are cool.
Tagged templates take the above function in a different way -
|
|
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 -
|
|
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! )