Back in the day, Everyone one of us was familiar with long string concatenations. With ES6, We got Template literals, which saved us a lot of time.
let currentTime = new Date().getHours();
let var1 = `I am template literal`;
let var2 = `I am multi template literal with the embedded expression:
${currentTime >23 || currentTime >5 ? 'I am night owl':'I am early bird'} `
A nice and elegant solution to our problems.
But wait, it is not the end of the story, there is one other cool feature, which is been used by many libraries like lit-elements, re-template-tag, graphql-tag
Tagged Templates
Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.
let you = 'Tony';
function html(strings,...values){
console.log(strings); // ['hi ',' have a great day.']
console.log(values); // ['Tony']
}
html`hi ${you}, have a great day.`
You can see it is a normal function but invoked in a different way.
You might also think that can be written in normal function, but imagine passing string and expressions as args and processing it for your requirements.
function html(concatenatedString, ...values){
// replace # with values sequentially
// do other stuff
// return result
}
html(`hi #, have a great day`,'Tony') // # acts as seperator
I don't see a need to write something like this when we have a better approach provided out of the box.
Where can I use it?
You can use Tagged templates in many scenarios
- Format a template literal into HTML elements
- Reusable templates
- Process paths and in localization
- Decorate the text with some default data.
Top comments (0)