liveBook · Manning

Lit-html

As explained in Web Components in Action

lit-html is a JavaScript library for efficiently rendering HTML templates with tagged template literals.

lit-html is an opt-in JavaScript library for managing HTML and CSS with tagged template literals. Import only the features a component uses instead of adopting a monolithic framework. section 6.6

Use lit-html to:

  • Generate readable multiline HTML from JavaScript template literals. section 6.8
  • Repeat markup from arrays with the repeat directive. section 6.6
  • Attach event listeners directly in rendered markup. section 6.8

Rendering repeated options

import {html} from './lit-html/lit-html.js'; import {repeat} from './lit-html/directives/repeat.js'; render(props) { return html`<select> ${repeat(props.logoChoices, i => i.id, i => html`<option value="${i.uri}">${i.name}</option>`)} </select>`; } The outer html tag defines the template; repeat turns each data item into an option. section 6.6

Listing 6.18. Injecting event listeners into markup using lit-html
render(controller, props) {
   return html`
           <div class="logo-picker">Logo:
               <select @change="${(e) => {                       #1
                 controller.updateGraphics()} }">
                   ${repeat(props.logoChoices, (i) => i.id, (i, index) =>
                    html`<option value="${i.uri}">${i.name}</option>
               `)}</select>
           </div>
           <div class="background-picker">Background:
               <select @change="${(e) => {                       #2
                 controller.updateGraphics()} }">
                   ${repeat(props.backgroundChoices, (i) => i.id, (i, index) =>
                    html`<option value="${i.uri}">${i.name}</option>
               `)}</select>
           </div>
           ${this.html(props)}
           ${this.css(props)}`;
},

Inspect the complete pattern for injecting change handlers into select elements while repeating their options. section 6.6

How Web Components in Action covers it

How deep it goes
Explains tagged templates, repeated markup, and event listeners through working examples, without detailing rendering internals.
Examples
Demonstrates repeated logo and background options plus inline change handlers in a business-card customizer.
What it assumes
Assumes JavaScript modules and Web Components, while teaching template literals and tagged-template syntax incrementally.
What you can do after
Apply via lit-html to render data-driven templates and attach event listeners inside Web Components.
How it connects
Connects tagged template literals, Web Components, LitElement, template rendering, and event listeners.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.