DEV Community

Cover image for Tagged Templates
Bharath Muppa for Entangled Cognition

Posted on

Tagged Templates

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

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

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

Enter fullscreen mode Exit fullscreen mode

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

  1. Format a template literal into HTML elements
  2. Reusable templates
  3. Process paths and in localization
  4. Decorate the text with some default data.

Further Reading

  1. Google docs
  2. MDN web docs

Top comments (0)