HTML Templates via JavaScript Template Literals

Avatar of Chris Coyier
Chris Coyier on (Updated on )

You know those super cool backticks-for-strings in new JavaScript?

let emotion = `happy`;
let sentence = `Chris is feeling ${emotion}`;

Besides the variable interpolation in there being mighty handy, the do multi-line strings wonderfully, making them great for chunks of HTML:

const some_html = `
  <div class="module">
    <h2>${data.title}</h2>
    <p>${data.content}</p>
  </div>
`;

That doesn’t look overly different than JSX does it?! Maybe we’d do something like that as a React component:

class MyModule extends React.Component {
  render() {
    return 
      <div class="module">
        <h2>{this.props.title}</h2>
        <p>{this.props.content}</p>
      </div>;
  }
}

But what if we don’t really need React, or any other fairly-large-ish JavaScript framework?

What if the only thing we want is the ability to render HTML templates and also really efficiently re-render them when we need to, like React is known for?

As far as I understand it, that’s what projects like lit-html are for. As I write, it’s a pretty new library from Google and the Polymer folks.

It allows you to define an HTML template with regular template literals, like this:

import { html, render } from './lit-html.js';

const helloTemplate = (data) => html`
  <div class="module">
    <h2>Hello ${data.name}!</h2>
    <p>${data.content}</p>
    </div>
`;

Then you call the render function, passing it that template, the data, and where you want it rendered:

let data = {
  name: "Chris",
  content: "Just trying to figure stuff out."
}

render(helloTemplate(data), document.body);

Then say the data changes… you call render again:

data.name = "Sammy";

render(helloTemplate(data), document.body);

And this is where lit-html shines. It’s smart enough to only update the parts of the DOM it needs to.

Here’s a little comparison where some data is changed, then the templates re-rendered. If we innerHTML the whole thing, well, the entire DOM is changed. With lit-html it just changes smaller inner parts.

Here’s a little video where you can see the DOM-updating difference:

lit-html on the left, “regular” on the right. Demo project.

There is another project along these lines too. I don’t know quite enough to judge, but it’s a bit older and I believe it’s a bit more robust. It’s called HyperHTML.

HyperHTML also allows you to create templates and render them. And most importantly rerender them efficiently.

Here’s a demo where the data comes from the Quotes on Design API and inserted into a template:

See the Pen Trying HyperHTML by Chris Coyier (@chriscoyier) on CodePen.

Kinda cool that these mini-libraries exist that do useful things for us, so when situations arise that we want a feature that a big library has, but don’t want to use the whole big library, we got smaller options.