Phil Zona Dot Net

ES6 template tags

One of my favorite ES6 features is the template literal. At face value, they're maybe not the most impressive thing in the world. But they do a lot for code readability, and, if you use them consistently, can be a helpful way to make sure you're sanitizing user inputs before sending them to the database.

The basics are pretty simple:

You use backticks to enclose the string, and inject in-scope variables with a bling and chicken-lips (a term I recently heard for curly braces, and will continue to use forever). That's actually a bit misleading - you can actually embed any valid JavaScript expression, not just variables.

But template literals are more than just a nice way to format your strings. They also have a feature called tagging, which I rarely see used.

I'm not sure where the term tagging came from, but a tag is just a function that you can apply to a template literal. Here's a super basic example that does the exact same thing as the code above:

This might seem silly, but notice the strings argument. This gives you an array of the "regular" parts of your string, meaning the pieces in between the expressions or variables. In the above example, the strings array has only one element, strings[0], and it contains My name is.

This has some pretty cool implications with longer strings and multiple expressions. For example, you could use a template literal to create a default string, but use a tag to manipulate output based on certain conditions:

For each of the template literals at the end, I'm using the same tag. The difference is in one of the expressions provided (favorite food). Depending on what the food is, I can change the ending of the sentence. If someone's favorite is pizza, they're congratulated. Conversely, if they're a broccoli fan, they will be scolded.

The point, however, is that in all of these cases, I'm still providing the same template as a base. The difference is whether the result uses string[2] or a custom value.

There are obviously better ways to achieve this exact output, but hopefully this begins to illustrate the power of of template tags. With a complex string (and remember, template literals make multiline strings really simple), you can create one base and manipulate it piece by piece with almost zero hassle.

Template tags are one of my favorite ES6 features, but one I don't see used very often. They're an awesome way to improve readability and generate complicated strings from a "starter" string, and here's the twist--you actually don't even have to return strings at all with a template tag. But that's a topic for another time 😎