Tagged templates literal in js.
Gilbish
Posted on March 28, 2021
What is template literal? πΆ
Template literals allow us to concatenate or embed variables inside a string. It was introduced in ES6.
Template literals are enclosed by the backtick.
Example:
const age = 12;
const title =`My age is ${age} years.`
What is Tagged templates literal? π¬
Here tag refers to a function which performs parsing of the given template literal.
styled components is a famous library that uses the tagged template literal.
Example:
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
How it works? π―
Step 1) Create a function.
const appendStyle = (array,val1,val2) => {
//do something and return a value.
return "testing";
}
can be also written as
const appendStyle = (array,...values) => {
//do something and return a value.
return "testing";
}
In the array we will get the split strings.
means if the template literal is My name is ${name} and my age is ${age}
then, the array will be
array = ['My name is','and my age is']
and in the values we will get all the arguments.
Step2) attach the function in front of the template literal, without the ()
const name = 'gilbish';
const age = '23';
const text = appendStyle`My name is ${name} and my age is ${age}`;
console.log(text);
// output: testing
Step3) finish the Function.
In the appendStyle function , we gonna make the color of each arguments to blue or whatever color you prefer. π
const appendStyle = (array,...values) => {
let color = "blue"
let text = '';
array.map((item,index) => text += `${item} <span style="color:${color}">${values[index] || ''}</span> `);
return text;
}
our tagged template literal appendStyle is ready to use π
Example:
const name = 'gilbish';
const age = '23';
const text = appendStyle`My name is ${name} and my age is ${age}`;
document.body.innerHTML = text;
Output:
Thanks for reading the post π
Posted on March 28, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.