DEV Community

Cover image for Tagged templates literal in js.
Gilbish
Gilbish

Posted on • Updated on

Tagged templates literal in js.

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.`
Enter fullscreen mode Exit fullscreen mode

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;
`;
Enter fullscreen mode Exit fullscreen mode

How it works? ๐Ÿ˜ฏ

Step 1) Create a function.

const appendStyle = (array,val1,val2) => {
   //do something and return a value.
   return "testing";
}
Enter fullscreen mode Exit fullscreen mode

can be also written as

const appendStyle = (array,...values) => {
   //do something and return a value.
   return "testing";
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Output:

Alt Text

Thanks for reading the post ๐Ÿ™

Top comments (0)