DEV Community

Cover image for Introduction to lit-html.js
Anurag Vohra
Anurag Vohra

Posted on

Introduction to lit-html.js

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>
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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.

  1. 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 strings tag`Some text ${some_var}` . Read the tagged template JS specification here at mozilla docs.
    So lit-html lib has created this html tags to help you convert your template string into DOM node tree.

  2. @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.

  3. 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.

Top comments (0)