HTML templating with <template> and ECMAScript 2015 template strings

The HTML5 <template> tag has been around for a few years and is fairly well-known and implemented. Elements inside a <template> tag are considered inert and do not get rendered or instantiated. The pattern is that your JavaScript will clone the elements inside when it wants to render them:

<template class="hello-template">

<div class="hello">

Hello, world!

</div>

</template> <script>

var helloTemplate = document.querySelector('.hello-template');

var helloDiv = document.importNode(helloTemplate.content, true);

document.querySelector('body').appendChild(helloDiv);

</script>

It’s a little verbose but still useful when you have bits of reusable markup in your document. But what if you have bits of reusable markup in your code? Template strings to the rescue!

var firstName = 'Andrew';

var lastName = 'Wizard';

var fullName = `<div class="full-name">

<em>${firstName}</em> <strong>${lastName}</strong>

</div>`;

document.querySelector('body').innerHTML = fullName;

Template strings are useful for a bunch of reasons:

They allow multi-line strings in JavaScript without hacks. They allow easier variable use without concatenation. The ${} substitution syntax can also evaluate any JavaScript expression, for instance 1 + 2.

I haven’t played with template strings as much as I’ve wanted to, but I imagine it wouldn’t be hard to make a vanilla JavaScript equivalent of Handlebars. It’d be a server-side script that takes HTML files with ${} substitutions, wraps them in backticks (`), and outputs them as JavaScript modules (see the next section) ready for immediate use.

(Update: Some have commented that this could leave you open to XSS, which is what I get for not playing around with it as much as I’d like! Make sure you thoroughly vet your web apps for security holes, especially when using newer technologies.)

This is as close as browsers have ever come to native, external HTML templates, and every major browser supports it! I’m really excited about this part of the stack.

Who has it?

Everybody has the <template> tag. As for who supports template strings: