I’m gonna be that guy. I’m not a fan of front-end JS frameworks. Angular and React are hard to learn, and can be very slow without proper optimizations, which can take months or years to understand. I have always much preferred a frameworkless approach that utilizes server-side rendering, and small tailored libraries for the front end magic I need.
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. — MDN
Here’s a basic use case scenario:
Whoa, what just happened? The variables were magically inserted into the string we defined. That’s terrific!
Now you might be saying: “But Hugo, I need my templates to render loops and show different content based on states. Should I just go cry in the bath tub?”
The answer is NO! I got you boo.
Following are a few simple techniques which makes it feel like you’re working with a fully fledged template engine.
Displaying content differently based on an expression.
Iterating through an array and rendering the contents of an item.
Array.map() iterates over our array, and returns a new array containing whatever we returned in each loop. By calling
.join('') on the result without a delimiter, we get a single string. We can also perform a
.trim() in the loop for good measure, avoiding inline-block spacing issues.
Repeat repeat repeating items.
Creating an empty iterable array is funky business. Don’t judge.
Using the same method as before, we
.map() through the array and
.join('') the result.
Putting it into practice
Here’s a small example using these techniques.
As you can see,
template literals can be nested within each other, creating markup (or other strings) with dynamic complexity.
template literals in multiple projects now, they have sparked my enthusiasm for client-side rendering. It feels like you’re using React, but without the overhead. That’s just plain neat.