HTML Templates via JavaScript Template Literals

JS
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:
js
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.

Comments