lit-html

Feb 26, 2019 · 372 words · 2 minute read

The debate over CSS in JS seems to be never-ending. But, when it comes to matters of what tools and what frameworks/libraries are helpful to come down to what does your project need and it will it satisfy those needs quickly and efficiently.

The Polymer Project has announced the first stable release of two interesting libraries lit-html and litElement. Today, we are going to be looking at lit-html which is a tiny library for HTML templating.

const myTemplate = (name) => html`
    <div>
      Hi, my name is ${name}.
    </div>
`;

render(myTemplate('Ada'), document.body);

To get things started let us look at this simple example from the documentation. The workflow is rather simple. Declare your template inside of a variable. Then you have a render function which allows you to declare your template and where you want it in the document. Pretty, simple and straight forward.

When it comes to making demos. Sometimes, I like to make things to be intentional kind of rough looking. It helps me see how things work and instantly see what is going on quickly.

So, let us walk through this example. There is going to be a full Codepen at the end of this. I started out by setting up a few empty divs we can access later for our templates.

<div class="header"></div>
<div class="content"></div>
<div class="footer"></div>

Next, lets import lit-html from unpkg.

import {html, render} from 'https://unpkg.com/[email protected]/lit-html.js';

I set up a template per each section. Let’s look at our header setup.

const myHeader = (color) => html`
   <style>
        #logo {
        background:${color};
}
</style>
       <div id="logo">
                <img src="https://imgplaceholder.com/350x125/ff7f7f/333333/fa-image">
    </div>
`;
render(myHeader('aliceblue'), 
             document.querySelector('.header'));

For our header, I figured our background color might be the thing we want to change the most often so we turned that into a variable that is going to be easily passed in a template such as the one above.

Below, you can see the full Codepen of our demo trying to render three different templates with the library. It was very efficient to work with and feels like it is flexible enough to bring in on a number of projects.

Also, for my resources here is a curated repo of resources for lit-html.

See the Pen LIT HTML by John Siwicki (@siwicki) on CodePen.