Introduction to lit-html.js
Anurag Vohra
Posted on May 10, 2021
lit-html is a templating library.
What do it means to be a templating library?
Templating Library helps you create DOM nodes/element at runtime.
If you have to create a DOM node tree like this at run time:
<body>
<!--START: create this at run time and append to body-->
<div id="myid1">
<div style="width:50px;height:50px:background-color:red;">
</div>
</div>
<!--END-->
</body>
Ordinarily without any templating library, you would have written a JS code something like this(not boasting to be an accurate code):
let div1 = document.createElement("div");
div1.id = "myid1";
div1.addEventListener("click",()=>{
alert("hello");
});
let div2 = document.createElement("div");
div2.style.width="50px";
div2.style.height="50px";
div2.style.backgroundColor="red";
div1.appendChild(div2);
body.appendChild(div1);
Too verbose and impractical for creating deeply nested node trees.
lit-html helps your create this JS code like this:
let mytemplate = html`
<div id="myid1" @click=${()=>alert("hello")}>
<div style="width:50px;height:50px:backgroundcolor:red;">
</div>
</div>
`;
render(mytemplate,document.body);
This code looks almost similar to the the Node tree we intended to create. Infact we have added an event listener too on the DOM.
Lets break down this code and understand whats happening.
html `...`
: this is a JS template string.
Many of the JS user is accustomed to template string like this`Some text ${some_var}`
, but the specification of template string also allows to add tags before this template stringstag`Some text ${some_var}`
. Read the tagged template JS specification here at mozilla docs.
So lit-html lib has created thishtml
tags to help you convert your template string into DOM node tree.@click=${()=>alert("hello")}
this helps you add event listeners to your DOM tree, at run time. Isn't it awesome. user of other libraries might be accustomed to similar syntax provided by there own libraries.render
function call. It has two arguments, one is the template and other is the place where this node tree created will be appended at run time.
Tutorial
There is no better tutorial for lit-html, than the (official documentation](https://lit-html.polymer-project.org/guide/getting-started). It will be hardly 1-2 hrs read and you be ready to use lit-html in your projects.
Posted on May 10, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.