The <template> tag is useful and performant, but it isn't packaged with the logic of the component, making it difficult to distribute a component in a single file.
Template elements also lend themselves to imperative code. In many cases this leads to less-readable code compared to declarative coding patterns.
This is where Lit templates comes in! Lit lets you write templates in JavaScript, then efficiently render and re-render those templates together with data to create and update DOM. It is similar to JSX and Virtual DOM libraries but it runs natively in the browser and much more efficiently than VDOM in many cases.
This tutorial uses only a few of the features supported by Lit templates.
For full coverage, see Templates in the Lit documentation.
Migrate the native web component <rating-element> to use a Lit template. Lit uses Tagged Template Literals – functions that take template strings as arguments with a special syntax.
Lit then uses <template> elements under the hood to provide fast rendering as well as providing some sanitization features for security.
Start by migrating the <template> in index.html into a Lit template by adding a render() method to the web component:
You may also delete your <template> from index.html.
In this render() method you define a variable called template and invoke the html tagged template literal function. Also notice the text ${this.rating} inside the span element. This is a Lit expression, and it takes the place of setting the span's innerText imperatively.
Additionally, you call the Lit render() method which synchronously renders the template into the shadow root. Every time the component's render() method is called, the rating value will be updated.
Eventually you won't have to call render() imperatively at all. For now, call this.render() in the connectedCallback and remove the logic related to inserting the template and setting the innerText on the .rating span:
Now all your logic and templating is packaged in a single location! In the next step, you will clean up all the imperative code by moving it to the template.