Tagged templates

A tagged template is a more advanced form of the templates we've been looking at. Basically, it's another way to call a function, but with a syntax similar to a template string. Let's look at an example and then explain it:

// Source file: src/tagged_templates.js

function showAge(strings, name, year)
{
const currYear = new Date().getFullYear();
const yearsAgo = currYear - year;
return (
strings[0] + name + strings[1] + year + `, ${yearsAgo} years ago`
);
}

const who = "Prince Valiant";
const when = 1937;
const output1 = showAge`The ${who} character was created in ${when}.`;
console.log(output1);
// The Prince Valiant character was created in 1937, 81 years ago

const model = "Suzuki";
const yearBought = 2009;
const output2 = showAge`My ${model} car was bought in ${yearBought}`;
console.log(output2);
// My Suzuki car was bought in 2009, 9 years ago

The showAge() function is called with the following:

  • An array of strings, corresponding to each constant part of the template, so strings[0] is The and strings[2] is . in the first case, for example
  • A parameter for each expression included; in our case, there's two of them

The function may do any calculations and return any type of value—possibly not a string! In our example, the function produces an enhanced version of the original string, adding how many years ago something happened—when a comic strip character was created or an automobile was bought, for example.

We'll be using tagged templates in the Creating StyledComponents for inline styling section of Chapter 7, Enhancing Your Application; the styled-component library we'll use depends totally on this feature to allow for more readable code.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.25.32