The power of Template Literals

pfacklam

Paul Facklam

Posted on February 19, 2020

The power of Template Literals

I'm pretty sure you've come across a template literal before. That's not surprising, since it's been almost 5 years after its release as one of the features of EMCAScript 6 in June 2015 (where they were once called template strings). Reasons enough to remind yourself what template literals are and what makes them so powerful and extremely useful.

Template Literals

Template literals are a perfectly simple way of creating strings and to perform interpolation on them. I guess that you are quite familiar with the syntax.

Template literals are enclosed by the backtick [...] character instead of double or single quotes.
-- Mozilla Developer Network

const double_quoted_string = "This is a common string."; // not a literal
const single_quoted_string = 'Also a common string'; // 
const literal_string = ``; // 
Enter fullscreen mode Exit fullscreen mode

I admit there is nothing special about template literals so far compared to normal strings. But there is more. Imagine you want to have a multi-line string. Is this possible with ordinary strings? Sure it is, but it's not fancy.

const multi_line_string = 'This is a common string.\n' +
'with more than one line.';
// "This is a common string.
// with more than one line."
Enter fullscreen mode Exit fullscreen mode

And here is the trick. If we use a template literal instead, we get this feature out of the box without any workarounds. But keep in mind that any whitespace or newline characters are part of the Template Literal.

const multi_line_literal = `This is a common string.
with more than one line.`;
// "This is a common string.
// with more than one line."
Enter fullscreen mode Exit fullscreen mode

Not impressed yet? Ok wait, I'll give you another example of how cool template literals can be. Placeholders!

Template literals can contain placeholders. These are indicated by the dollar sign and curly braces.
-- Mozilla Developer Network

Gone are the days when you had to laboriously concatenate strings by hand. Now it is just defining the placeholder via ${} and providing the values. That's it!

const num = 3;
const str = "square";
const func = (i) => { return i * i };
const output = `The ${str} of ${num} is ${func(num)}`;
// "The square of 3 is 9"

// ES 5 equivalent
var output_es5 = 'The ' + str + ' of ' + num + ' is ' func(num);
// "The square of 3 is 9"
Enter fullscreen mode Exit fullscreen mode

How cool is this? And there is still more! Template Literals give developers the possibility to create complex strings that can be used for templating. Both nested templates and conditional templating are conceivable.

const item = {
  isExpanded: true,
  content: "This text can only be seen when expanded."
};
const cssClasses = (isExpanded) => `collapsible ${isExpanded ? 'is-expanded' : ''}`;
const collapsible = `
  <div class="${cssClasses(item.isExpanded)}">
    ${item.content}
  </div>
`;
Enter fullscreen mode Exit fullscreen mode

And now the grand finale... If I turn my literal for the collapsible into a function (as I did for the CSS classes), I would be able to output a whole list of items instead of a single one with the help of Array.map. Mind blowing!

const items = [{
  isExpanded: true,
  content: "This text can only be seen when expanded."
}];
const cssClasses = (isExpanded) => `collapsible ${isExpanded ? 'is-expanded' : ''}`;
const collapsible = (item) => `
  <div class="${cssClasses(item.isExpanded)}">
    ${item.content}
  </div>
`;
const list = `
  ${items.map((item) => {
    return collapsible(item);
  })}
`;
Enter fullscreen mode Exit fullscreen mode

Tagged Template Literals

I guess you know what's coming... And you are right. There is still more. 😎 Are you ready for this? Then let's dive in!

A very powerful feature of template literals (and I guess most developers are not aware of this) is the possibility to tag them. In this case we talk about tagged template literals. But what does this mean? It means that you can pass a template through a predefined function.

The tag function can then perform whatever operations on these arguments you wish, and return the manipulated string.
-- Mozilla Developer Network

It does not necessarily have to be a string. The result of the function can also be something different. The name of the function is arbitrary and completely up to you.

The first parameter is of type array and contains the strings. The remaining arguments are related to the expressions.


const topic = 'Template Literals';
const rating = 5;

function rate(strings, topicExp, ratingExp) {
  const str0 = strings[0]; // "'"
  const str1 = strings[1]; // "' is an " 
  const str2 = strings[2]; // " topic."

  let ratingStr;
  if (ratingExp > 4){
    ratingStr = 'awesome';
  } else {
    ratingStr = 'average';
  }

  return `${str0}${topicExp}${str1}${ratingStr}${str2}`;
}

const output = rate`'${topic}' is an ${rating} topic.`;

// 'Template Literals' is an awesome topic.
Enter fullscreen mode Exit fullscreen mode

Please note that this is a just very basic example to demonstrate the mechanisms behind the scenes. There are a lot of use cases where it really makes sense to work with tagged template literals:

  • Escaping HTML tags
  • Translation and internationalization
  • Highlighting in texts

Summary

I admit that this was a lot to digest for a basic introduction. Do you remember everything? Time for a recap. Template literals:

  • are made with backticks
  • are multi-line-ready
  • can have placeholders and their values can even be funtions
  • can be used for conditional and nested templating
  • can be used for advanced interpolation

Finally, I would like to thank you for your time and interest in this article. I hope that you enjoyed reading it.

πŸ’– πŸ’ͺ πŸ™… 🚩
pfacklam
Paul Facklam

Posted on February 19, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related