completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Lit templates

Learn Lit template expressions with live examples: child values, attributes, .property, @event and ?boolean bindings, element refs, and static html.

By the end, you can
  • 01
    Write all six kinds of expressionPut values in text, attributes, .properties, @events, ?boolean attributes, and element directives such as ref().
  • 02
    Pick the right bindingKnow why value= stops following a box once someone types, and why disabled=${false} still disables a button.
  • 03
    Know where expressions can't goSpot holes in tag names, attribute names, <template>, and <textarea>, and use lit/static-html.js when you truly need one.

What are Lit templates?

Asha is putting the Leaf and Kettle menu online. Each tea gets a <tea-menu-item>, built with Lit. Ravi reads her template and stops. "Some of these attributes start with a dot. Others start with @ or ?. What do they mean?"

Where can a value go in a Lit template? And what does Lit do with it there?

A Lit template is HTML written in an html tagged template. Each ${} in it is an expression. Where the expression sits decides what Lit does with its value: text, an attribute, a property, an event listener, a boolean attribute, or an element directive.

Here is Asha's first menu item:

A first Lit menu item, Sencha for 4 EURPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha" price="4"></tea-menu-item><button id="swap">Show Assam</button><script type="module">  import "./tea-menu-item.js";  const item = document.querySelector("tea-menu-item");  await item.updateComplete;  const heading = item.shadowRoot.querySelector("h3");  document.querySelector("#swap").addEventListener("click", async () => {    item.name = "Assam";    await item.updateComplete;    console.log(`Same h3: ${item.shadowRoot.querySelector("h3") === heading}`);  });</script>
ResultLoading…
  • Lines 1 to 3 are the import map from lesson 20.1. The name lit means Lit 3.3.3, from esm.sh.
  • Line 4 is the menu item, with a name and a price. Line 5 is a button.
  • Line 9 waits for the first render. Line 10 keeps the item's heading.
  • Line 12 changes the name. Line 14 checks that the heading is still the same element.

The tea-menu-item.js tab holds the component:

tea-menu-item.js: a template with two expressionsJavaScript
import { LitElement, html } from "lit";

export class TeaMenuItem extends LitElement {
  static properties = {
    name: {},
    price: { type: Number },
  };

  render() {
    return html`<h3>${this.name}</h3>
      <p>Price: ${this.price} EUR</p>`;
  }
}

customElements.define("tea-menu-item", TeaMenuItem);
  • Lines 4 to 7 declare two reactive properties, as in lesson 20.2.
  • Lines 10 and 11 are the template. html is Lit's tag. Each ${} is a hole for one value.
  • this.name sits between two tags, so it becomes text. So does this.price.

The item shows Sencha and Price: 4 EUR. Press Show Assam. The heading says Assam, and the console prints Same h3: true.

Lit didn't build a new heading. It kept the HTML it made the first time, and wrote one new value into it. Your own html.js did the same in lesson 18.2. Lit's docs say it too: Lit parses and creates the static HTML once, then only updates the values that changed (Lit).

Three rows. Top: two cards with blanks, <h3>____</h3> and <p>Price: ____ EUR</p>, labeled printed once: the template's strings. Middle, labeled first render: cards Sencha and 4, with arrows up into the blanks. Bottom, labeled after Show Assam: a card Assam, and a crossed-out card 4, labeled the same 4, skipped.printed once: the template's strings<h3>____</h3><p>Price: ____ EUR</p>first renderSencha4after Show AssamAssam4the same 4, skipped
Lit prints the template's fixed HTML once. The first render fills both blanks. After Show Assam, only the name is new, so Lit writes only Assam. The price is the same 4, so Lit skips it.
Real-life analogyAn order slip with blanks

Leaf and Kettle's order slips come from the printer in a stack. Each one says "Tea: ____ Cups: ____". For each order, Ravi only writes in the blanks. If the next order is the same tea, he leaves that blank alone.

In real life: The printed slip
In JavaScript: The template's fixed HTML, made once
In real life: The blanks on it
In JavaScript: The ${} expressions
In real life: Writing in one blank
In JavaScript: Lit writing one value
In real life: Leaving a blank as it is
In JavaScript: Lit skipping a value that didn't change
The main idea

A Lit template is printed once. Each ${} is a blank on it. Where the blank sits decides how Lit writes the value. On each render, Lit fills in only the blanks whose value changed.

A blank can sit in six places. Each has its own section below:

  • Between two tags: a child expression.
  • In an attribute's value: an attribute expression.
  • After a dot, like .value=${…}: a property expression.
  • After an at sign, like @click=${…}: an event listener expression.
  • After a question mark, like ?disabled=${…}: a boolean attribute expression.
  • Alone inside a tag, like <button ${ref(…)}>: an element expression.

What can a child expression render in Lit?

A child expression sits between an element's tags, where child nodes go. Lit's docs list what it takes (Lit):

  • strings, numbers, and other plain values;
  • templates made with html;
  • DOM nodes;
  • arrays, and other lists you can loop over, of any of these;
  • nothing, Lit's value for "render no node here".

Pick a value, and see what lands in the paragraph:

Playground: one child expression, six values
Render one value after Today, and print what the paragraph holdsPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><p id="note"></p><script type="module">  import { html, nothing, render } from "lit";  const note = document.querySelector("#note");  const value = "<b>Sencha</b>";  render(html`Today: ${value}`, note);  console.log(`Text: "${note.textContent}"`);  console.log(`Elements: ${note.children.length}`);</script>
ResultLoading…
Try it yourself
A string is text, tags and all

It prints Text: "Today: <b>Sencha</b>" and Elements: 0. Lit put the string in a text node, so the tags show as letters.

Only line 8 changes. The page prints the paragraph's text and how many elements it holds.
  • Line 8 is the value. Your choice changes it.
  • Line 9 renders it after the word Today. render() is lit-html's own function from lesson 20.1.
  • Lines 10 and 11 print the paragraph's text and how many elements it holds.

A string with tags prints Text: "Today: <b>Sencha</b>" and Elements: 0. A template prints Text: "Today: Sencha" and Elements: 1. undefined and nothing both print Text: "Today: ".

A string is always text. Lit puts it in a text node, which shows its characters as they are. So a tea name a user typed can't add tags to your page. Lesson 18.2 showed why, and how unsafeHTML() turns a string you trust into markup.

Only a template makes elements. A number becomes its digits. An array renders each item in turn, as your kit's list holes did in lesson 18.3. Conditions and lists in Lit have their own lesson, next in the Lit stage.

Four values render nothing at all: nothing, null, undefined, and "". Lit writes no node, not even an empty one. Lit's docs say this matters for a slot with fallback content: with no node, the fallback still shows (Lit).

Composing templates

A template is a value, so a template can hold other templates. Lit's docs call this composing (Lit). Here the menu item's template is split into three methods:

The menu item as three small templatesJavaScript
nameTemplate() {
  return html`<h3>${this.name}</h3>`;
}

priceTemplate() {
  return html`<p>Price: ${this.price} EUR</p>`;
}

render() {
  return html`${this.nameTemplate()} ${this.priceTemplate()}`;
}
  • Lines 1 to 3 return the name's template. Lines 5 to 7 return the price's template.
  • Line 10 puts both into one template, as two child expressions.

Put these lines in place of render() in the first example's tea-menu-item.js tab. It shows the same item, and Show Assam still prints Same h3: true. Lit's docs add that a subclass can replace one of these methods.

The same docs give render() a few rules. Use only the component's properties. Change no state. Return the same result for the same values. And render() may return anything a child expression takes, not only a template (Lit).

How do attribute bindings work in Lit?

An expression in an attribute's value sets that attribute (Lit). It can be the whole value, with no quotes. Or it can be part of a value, inside quotes. This page uses both:

One label, four times, with whole and partial attribute valuesPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><div id="out"></div><script type="module">  import { html, nothing, render } from "lit";  const out = document.querySelector("#out");  function show(kind, note) {    render(html`<span class="tag ${kind}" title=${note}>Tea</span>`, out);    console.log(out.querySelector("span").outerHTML);  }  show("green", "Grassy");  show("black", undefined);  show("black", nothing);  show(nothing, "Malty");</script>
ResultLoading…
  • Line 9 is the template. class joins the text tag and the kind. title is the whole value.
  • Lines 8 to 11 render the label and print its HTML. Lines 12 to 15 call it four times.

It prints four lines:

  1. <span class="tag green" title="Grassy">Tea</span>
  2. <span class="tag black" title="">Tea</span>
  3. <span class="tag black">Tea</span>
  4. <span title="Malty">Tea</span>

Line 13 passed undefined, and the title became empty. In an attribute, Lit writes an empty string for undefined and null. Line 14 passed nothing, and the title went away. Line 15 put nothing in the class, and the whole class went, its fixed text too. One nothing anywhere in a value removes the attribute (Lit).

Why it matters: undefined often means "no value yet". When the attribute should go away then, pass nothing. Lit has a directive for this. A directive is a function that changes how Lit handles one expression:

ifDefined: no title when the note is undefined or nullJavaScript
import { ifDefined } from "lit/directives/if-defined.js";

html`<span title=${ifDefined(note)}>Tea</span>`;

Line 1 imports it. Line 3 wraps the note. if-defined.ts is one line: value ?? nothing (line 15). So ifDefined(undefined) and ifDefined(null) remove the title. ifDefined("") keeps an empty one, because ?? only replaces null and undefined.

What is the difference between .value and value in Lit?

Lesson 5.1 showed that a text box's value attribute is only its starting text. The text in the box now is the value property. Lit gives you a binding for each. This tea note has both:

Two text boxes: one bound to the attribute, one to the propertyPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-note></tea-note><script type="module" src="./tea-note.js"></script>
ResultLoading…

Line 4 is the note. Line 5 loads the tea-note.js tab, which holds the component:

tea-note.js: value and .valueJavaScript
import { LitElement, html } from "lit";

class TeaNote extends LitElement {
  static properties = { note: {} };

  constructor() {
    super();
    this.note = "No sugar";
  }

  render() {
    return html`<label>Attribute <input value=${this.note}></label>
      <label>Property <input .value=${this.note}></label>
      <button @click=${() => (this.note = "Less sugar")}>Use the house note</button>`;
  }
}

customElements.define("tea-note", TeaNote);
  • Line 12 binds the value attribute of the first box.
  • Line 13 binds the value property of the second box. The dot in front makes it a property expression.
  • Line 14 is a button that sets the note to Less sugar.

Click at the end of each box, and type "please" after a space. Then press Use the house note. The Attribute box still shows No sugar please. The Property box shows Less sugar. Without typing, both boxes would change.

Here is why. The HTML Standard gives each box a dirty value flag (HTML). Typing sets it. Once it's set, a new value attribute no longer changes the text. Lit did write Less sugar into the first box's attribute. The box just stopped following it. The second box got box.value = "Less sugar", which always changes the text.

Two halves after you typed please and pressed the button. Left, value=${note}: a card value="Less sugar", labeled the attribute, only a default, with an arrow down to the box, which still shows No sugar please. Right, .value=${note}: a card value: Less sugar, labeled the property, what the box holds, with an arrow down to the box, which shows Less sugar.value=${note}value="Less sugar"the attribute, only a defaultNo sugar pleasethe box keeps your typing.value=${note}value: Less sugarthe property, what the box holdsLess sugarthe box shows it
Both bindings got Less sugar. On the left, it went into the attribute, which only sets the starting text, so the box kept your typing. On the right, it went into the property, which is the box's text.
Real-life analogyA grey suggestion on an order form

Leaf and Kettle's order form has a suggestion printed in grey: No sugar. A customer writes over it. Later, the shop prints a new grey suggestion, Less sugar. The customer's writing stays on top. Only writing on the form changes what it says.

In real life: The grey suggestion printed on the form
In JavaScript: The value attribute
In real life: What is written on the form
In JavaScript: The value property: the text in the box
In real life: A customer writing over the suggestion
In JavaScript: Typing, which sets the dirty value flag
In real life: Reprinting the grey suggestion
In JavaScript: value=${note}
In real life: Writing on the form yourself
In JavaScript: .value=${note}

Lit's docs say a property expression does the same as setting the property yourself, like input.value = … (Lit). And Lit keeps the case of the name, though HTML attribute names have no case.

Passing data to a child component

A property can also carry what an attribute can't: arrays, objects, and functions. This page hands one array to two components:

The same array, as a property and as an attributePop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><div id="order"></div><script type="module">  import { html, render } from "lit";  import "./tea-extras.js";  const extras = ["milk", "honey"];  render(html`<p><tea-extras .extraNames=${extras}></tea-extras></p>    <p><tea-extras extraNames=${extras}></tea-extras></p>`, document.querySelector("#order"));</script>
ResultLoading…
tea-extras.js: count the extras, and name their kindJavaScript
import { LitElement, html } from "lit";

class TeaExtras extends LitElement {
  static properties = { extraNames: {} };

  constructor() {
    super();
    this.extraNames = [];
  }

  render() {
    const kind = Array.isArray(this.extraNames) ? "an array" : `a ${typeof this.extraNames}`;
    return html`${this.extraNames.length} extras, from ${kind}`;
  }
}

customElements.define("tea-extras", TeaExtras);
  • Page line 9 passes the array as .extraNames, a property. Line 10 passes it as extraNames, an attribute.
  • In the tea-extras.js tab, line 12 names the kind of value. Line 13 counts its items.

The first shows 2 extras, from an array. The second shows 10 extras, from a string.

The attribute turned the array into the text milk,honey, ten characters long. The property kept the real array. Why it matters: give objects and arrays to child components with a dot.

When does Lit write a property again?

Lit compares each value with the last value it wrote. It never reads the box. Try this in the tea note. Press Use the house note. Type "please" after Less sugar in the Property box. Press the button again. The box keeps Less sugar please. The note was already Less sugar, so Lit had nothing new to write. Lit's live() directive checks the page instead (Lit). It comes in a later lesson of the Lit stage.

How do you add an event listener in a Lit template?

Put @ and the event's name before an expression (Lit). Lit's docs say it's like calling addEventListener() on that element. The value is the listener: a function, or an object with a handleEvent() method, as addEventListener() takes.

A menu item with two click listenersPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha"></tea-menu-item><script type="module" src="./tea-menu-item.js"></script>
ResultLoading…
tea-menu-item.js: a method, and an object with onceJavaScript
import { LitElement, html } from "lit";

export class TeaMenuItem extends LitElement {
  static properties = {
    name: {},
    cups: { state: true },
  };

  constructor() {
    super();
    this.cups = 0;
  }

  add() {
    this.cups += 1;
    console.log(`this is <${this.localName}>`);
  }

  render() {
    return html`<h3>${this.name}</h3>
      <button @click=${this.add}>Add to cart</button>
      <button @click=${{ handleEvent: () => console.log("A free sample, poured"), once: true }}>Free sample</button>
      <p>In cart: ${this.cups}</p>`;
  }
}

customElements.define("tea-menu-item", TeaMenuItem);
  • Line 21 listens for clicks with the add() method. Lines 14 to 17 are add().
  • Line 22 listens with an object. Its handleEvent() prints a line. once: true is an option, as in addEventListener(): the listener runs one time.
  • Line 23 shows the cups.

Click Add to cart twice. It shows In cart: 2, and the console prints this is <tea-menu-item> twice. Click Free sample twice. A free sample, poured prints only once.

Line 16 used this, and it was the component. add() was passed as it is, with no bind(). Lit's docs say a listener in a Lit component is bound to the component. In the source, every LitElement renders with { host: this } (lit-element.ts, line 137). Lit then calls a listener function with that host as this (lit-html.ts, lines 2112 to 2118).

Real-life analogyA doorbell wired to the shop

Leaf and Kettle has a doorbell by its front door. Anyone can press the button. The bell always rings inside the shop that fitted it, so Asha hears it at the counter.

In real life: The bell button on the door
In JavaScript: The button with @click
In real life: The shop that fitted the bell
In JavaScript: The component that rendered the template
In real life: The bell ringing inside that shop
In JavaScript: Lit calling add() with the component as this

An object listener is different. Lit calls the object's own handleEvent(), so this inside it is the object. Use an arrow function there when you need the component, as line 22 does.

You can also write an arrow function in the template, like @click=${() => this.add()}. A new function on each render doesn't mean new listeners. Lit adds one listener of its own, once, and calls the function you gave last (lines 2020 to 2030). It adds itself again only when once, capture, or passive change (lines 2069 to 2076). Events in Lit, with their options and your own events, get a full lesson later in the stage.

How do you set a boolean attribute in Lit?

Some attributes work by being there: disabled, hidden, checked. Their text doesn't matter. This page binds disabled two ways, both to false:

disabled bound as a plain attribute and with ?Pop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><div id="out"></div><script type="module">  import { html, render } from "lit";  const out = document.querySelector("#out");  const soldOut = false;  render(html`<button disabled=${soldOut}>Plain</button>    <button ?disabled=${soldOut}>With ?</button>`, out);  for (const button of out.querySelectorAll("button")) {    console.log(`${button.textContent}: disabled is ${button.disabled}`);  }</script>
ResultLoading…
  • Line 8 says the tea is in stock.
  • Line 9 binds disabled as a plain attribute. Line 10 binds it with ? in front.
  • Lines 11 to 13 print each button's disabled property.

It prints Plain: disabled is true and With ?: disabled is false. The Plain button is greyed out.

The plain binding wrote the text false into the attribute: disabled="false". An attribute that is there disables the button, whatever it says. The ? binding calls toggleAttribute(). It adds the attribute for a truthy value and removes it for a falsy one (lines 2010 to 2013).

Two halves. Left, disabled=${false}: a card disabled="false", with an arrow down to a card greyed out, labeled still disabled. Right, ?disabled=${false}: a crossed-out card no disabled attribute, with an arrow down to a card can be pressed, labeled enabled.disabled=${false}disabled="false"greyed outstill disabled?disabled=${false}no disabled attributecan be pressedenabled
A disabled attribute works by being there, whatever its text says. ?disabled takes it away for false, so the button can be pressed.
Real-life analogyA Closed sign on the door

The shop hangs a Closed sign when it shuts. One morning, someone writes "not closed" on it and hangs it anyway. Customers see a sign on the door and walk away. To open, you take the sign down.

In real life: The sign on the door
In JavaScript: The disabled attribute
In real life: Writing "not closed" on the sign
In JavaScript: disabled="false"
In real life: Customers seeing a sign at all
In JavaScript: The browser checking only that the attribute is there
In real life: Taking the sign down
In JavaScript: ?disabled=${false}

Truthy means JavaScript treats the value as true. The string "no" is truthy, so ?disabled=${"no"} adds the attribute. 0, "", null, undefined, and nothing remove it.

How do you get a reference to an element in Lit?

An element expression sits inside a tag, on its own, with no name before it (Lit). It gets the whole element. It only takes directives. Lit's docs name ref() as a built-in one: it hands you the element.

Add to cart moves focus to the Steep buttonPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><tea-menu-item></tea-menu-item><script type="module" src="./tea-menu-item.js"></script>
ResultLoading…
tea-menu-item.js: a ref on the Steep buttonJavaScript
import { LitElement, html } from "lit";
import { createRef, ref } from "lit/directives/ref.js";

export class TeaMenuItem extends LitElement {
  steepButton = createRef();

  add() {
    this.steepButton.value.focus();
    console.log(`Focus is on ${this.shadowRoot.activeElement.textContent}`);
  }

  render() {
    return html`<button @click=${this.add}>Add to cart</button>
      <button ${ref(this.steepButton)}>Steep</button>`;
  }
}

customElements.define("tea-menu-item", TeaMenuItem);
  • Page line 2 maps lit/ too, so the tab's line 2 can import createRef() and ref().
  • Line 5 makes a ref: an object whose value will hold an element.
  • Line 14 is the element expression. ref() puts the Steep button into this.steepButton.value.
  • Line 8 moves focus to it. Line 9 prints where focus is.

Press Add to cart. The console prints Focus is on Steep.

ref() fills in value during the render (ref.ts, lines 52 to 67), so it's ready before anyone can click. You can also give ref() a function. Lit calls it with the element:

A ref callback that prints the element's textJavaScript
html`<button ${ref((button) => console.log(`Got ${button.textContent}`))}>Steep</button>`;

Line 1 passes ref() a function. It prints Got Steep when the button renders. Any other value in an element expression does nothing. <button ${"hello"}> renders a plain <button>, with no error, even in Lit's development build. Lit's ElementPart only runs directives (lines 2153 to 2162). More directives come in a later lesson of the stage.

Real-life analogyA name card on a seat

Before a tasting, Asha puts a name card on one chair. Later she doesn't search the room for it. She reads the card and walks straight to that seat.

In real life: The name card
In JavaScript: The ref, this.steepButton
In real life: Putting it on one chair
In JavaScript: ${ref(this.steepButton)} on the Steep button
In real life: Walking straight to that chair
In JavaScript: this.steepButton.value.focus()

Where can't you put an expression in a Lit template?

Lesson 18.2 found that a hole only works where its marker survives the browser's parser. Lit's docs put it simply: expressions go where attribute values and child elements go (Lit). Lit's development build checks templates more than its normal build. This playground loads it with ?dev:

Playground: four places an expression can't go
Render a value in a bad place, and print the result or the errorPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3?dev" } }</script><div id="out"></div><script type="module">  import { html, render } from "lit";  const out = document.querySelector("#out");  const value = "h3";  try {    render(html`<${value}>Sencha</${value}>`, out);    const element = out.firstElementChild;    console.log(`Rendered <${element.localName}> with ${element.attributes.length} attributes: ${element.textContent}`);  } catch (error) {    console.log(`Error: ${error.message}`);  }</script>
ResultLoading…
Try it yourself
A tag name throws

It prints Error: Bindings in tag names are not supported, and a link to static expressions. Lit's development build checks the template before the browser parses it.

Only lines 8 and 10 change. The page prints what rendered, or the error.
  • Line 2 loads Lit's development build.
  • Line 8 is a value. Line 10 puts it in a template. Your choice changes both.
  • Line 12 prints what rendered. Line 14 prints the error.

A tag name prints Error: Bindings in tag names are not supported. Please use static templates instead., with a link. An attribute name prints Rendered <p> with 0 attributes: Sencha. Inside a template, it prints Error: Expressions are not supported inside `template` elements. Inside a textarea, it only warns, then renders the text.

Each case, in plain words:

  • A tag name throws in the development build (lines 860 to 866). The normal build doesn't check. It draws an element named after Lit's marker, like <lit$855327437$>.
  • An attribute name does nothing, with no warning. Lit reads that hole as an element expression (lines 1032 to 1037), which ignores plain values.
  • Inside a <template> throws (lines 994 to 1005). Lit never walks into a template's content.
  • Inside a <textarea> warns. Typing in the box breaks the text Lit placed there. Bind .value instead.
  • Lit's docs add two more. Inside an element with contenteditable, bind .innerText instead. Inside an HTML comment, Lit never updates the value (Lit).

Every choice also prints Lit's "Lit is in dev mode" warning. Build with the development build, and ship the normal one.

How do you use a dynamic tag name in Lit?

Sometimes you need a tag that changes, like h2 or h3. Lit's answer is a static expression (Lit). Import a different html from lit/static-html.js, and mark the tag with literal:

A static tag name, h2 and then h3Pop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><div id="out"></div><script type="module">  import { render } from "lit";  import { html, literal } from "lit/static-html.js";  const out = document.querySelector("#out");  const heading = (tag) => html`<${tag}>Sencha</${tag}>`;  render(heading(literal`h2`), out);  const first = out.firstElementChild;  render(heading(literal`h3`), out);  console.log(`Now: <${out.firstElementChild.localName}>`);  console.log(`Same element: ${out.firstElementChild === first}`);</script>
ResultLoading…
  • Line 7 imports the static html and literal.
  • Line 9 puts the tag where a tag name goes.
  • Lines 10 and 12 render it with literal`h2`, then literal`h3`.
  • Lines 13 and 14 print the tag, and whether the element is the same one.

It prints Now: <h3> and Same element: false.

A static value joins the template's strings before Lit reads them (static.ts, lines 114 to 169). So h2 and h3 make two different templates, and changing one builds new elements. Lit's docs say to keep static values for things that rarely change, and to keep them out of reactive properties.

literal only takes text written in your code. For a string from somewhere else, there is unsafeStatic():

unsafeStatic: a tag name from a stringJavaScript
import { html, unsafeStatic } from "lit/static-html.js";

// Only a tag name your own code chose. Never anything a user typed.
const tag = unsafeStatic(settings.headingTag);
html`<${tag}>Sencha</${tag}>`;

Line 4 wraps a string your settings chose. Line 5 uses it as the tag. The string goes into the template as HTML, with no checks (static.ts, lines 68 to 71). Lit's docs warn that a user's string there could run code in your page.

One slip is common: html from lit with literal from lit/static-html.js. The development build warns: Static values 'literal' or 'unsafeStatic' cannot be used as values to non-static templates. Exercise 6 has this bug.

How does Lit decide what each binding does?

Two steps happen. html`` only collects the strings and the values. Then render() turns each expression into a part: an object that knows one place in the page and how to write there. This page shows both steps:

Two renders of one slip, and the changes the page sawPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><div id="out"></div><script type="module">  import { html, render } from "lit";  const out = document.querySelector("#out");  const slip = (tea, cups) => html`<p class="slip">${tea}: ${cups} cups</p>`;  const first = slip("Sencha", 2);  const second = slip("Assam", 2);  console.log(`Same strings: ${first.strings === second.strings}`);  console.log(`Values: ${second.values.join(", ")}`);  render(first, out);  const watcher = new MutationObserver(() => {});  watcher.observe(out, { subtree: true, childList: true, characterData: true, attributes: true });  render(second, out);  console.log(`Changes: ${watcher.takeRecords().map((change) => change.type).join(", ")}`);</script>
ResultLoading…
  • Line 8 is a template function. Lines 9 and 10 make two results, Sencha and Assam.
  • Line 11 compares their strings. Line 12 prints the second one's values.
  • Lines 13 to 17 render one, then the other, and print each change the page saw.

It prints Same strings: true, Values: Assam, 2, and Changes: characterData.

The strings are one frozen array, the same every time the template runs, as lesson 18.2 found. Lit keeps its prepared templates under that array (line 688). Only the values change. On the second render, Lit compared each value with the last one it wrote. Only the tea was new, so the page saw one change: one text node's data.

The way Lit writes comes from the part. When Lit first prepares a template, it walks its elements. For each bound attribute, this code picks the part:

How a prefix picks the part: lit-html.ts, lines 1016 to 1030, at lit 3.3.3TypeScript
const m = /([.?@])?(.*)/.exec(realName)!;
parts.push({
  type: ATTRIBUTE_PART,
  index: nodeIndex,
  name: m[2],
  strings: statics,
  ctor:
    m[1] === '.'
      ? PropertyPart
      : m[1] === '?'
        ? BooleanAttributePart
        : m[1] === '@'
          ? EventPart
          : AttributePart,
});

In plain words, line by line:

  1. Line 1 splits the attribute's name. m[1] is the prefix: a dot, a question mark, an at sign, or nothing. m[2] is the rest of the name.
  2. Lines 2 to 6 record a part for this element, under the name without its prefix.
  3. Lines 7 to 14 choose the part's class: PropertyPart for a dot, BooleanAttributePart for ?, EventPart for @, and AttributePart for no prefix.

Each class writes its own way. PropertyPart sets element[name] (line 1992). BooleanAttributePart calls toggleAttribute() (lines 2010 to 2013). EventPart adds itself as the listener (lines 2102 to 2108). A bare ${} inside a tag gets an ElementPart (lines 1032 to 1037).

Four rows under the headings You write, Lit makes, and It calls. class= goes to AttributePart, which calls setAttribute(). .amount= goes to PropertyPart, which sets element.amount =. ?disabled= goes to BooleanAttributePart, which calls toggleAttribute(). @click= goes to EventPart, which calls addEventListener().You writeLit makesIt callsclass=AttributePartsetAttribute().amount=PropertyPartelement.amount =?disabled=BooleanAttributeParttoggleAttribute()@click=EventPartaddEventListener()
Lit reads the first character of each bound attribute's name. A dot, a question mark, or an at sign picks a different part, and each part writes the value its own way.

Read each row across: what you write, the part Lit makes, what it does, and what your own html.js did.

Each kind of binding in Lit
What you writeThe part Lit makesWhat Lit does with the valueThe kit's html.js, from lesson 18.2
<h3>${name}</h3>ChildPartIt writes text, a template, a node, or a list. For nothing, null, undefined, or "", it writes no node.It writes text, or a list since lesson 18.3.
class=${kind}AttributePartIt calls setAttribute(). For nothing, it removes the attribute.It calls setAttribute().
class="tag ${kind}"AttributePartIt joins the text and the values into one value. One nothing removes the whole attribute.It stops with its error: a hole must be the whole value.
.amount=${price}PropertyPartIt sets element.amount.It sets the property too.
?disabled=${soldOut}BooleanAttributePartIt calls toggleAttribute(): on for a truthy value, off for a falsy one.It has no ? binding.
@click=${add}EventPartIt listens once, and calls your listener with the host as this.It removes the old listener and adds the new one.
<button ${ref(steep)}>ElementPartIt runs the directive with the element. It ignores any other value.It has no element binding.

Does Lit use a virtual DOM?

No. Lit doesn't build a second copy of the page to compare with the first. Each render gives it a list of values, and each part compares its new value with the one it wrote last. Lit's design doc calls this diffing "at the value level" (Lit). A string or number equal to the last one costs no work in the page at all.

Besides html, Lit has svg for pieces of an SVG image, and since Lit 3.2.0, mathml for math (changelog). Templates like these may reach the platform one day: Justin Fagnani has proposed a templating API for the DOM itself, built on tagged templates (his post).

Building a tea menu item with all six bindings

Asha's real menu item uses every kind. Sencha is in stock. Gyokuro is sold out. The price is the kit's tea-price, and the cart is the kit's tea-cart from lesson 14.5.

Two menu items and the kit's cartPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><tea-menu-item name="Sencha" price="4"></tea-menu-item><tea-menu-item name="Gyokuro" price="9" sold-out></tea-menu-item><tea-cart></tea-cart><script type="module">  import "./tea-kit/index.js";  import "./tea-menu-item.js";  const cart = document.querySelector("tea-cart");  document.addEventListener("tea-add", (event) => cart.add(event.detail));</script>
ResultLoading…
tea-menu-item.js: all six kinds of expressionJavaScript
import { LitElement, html, css } from "lit";
import { createRef, ref } from "lit/directives/ref.js";

export class TeaMenuItem extends LitElement {
  static properties = {
    name: {},
    price: { type: Number },
    soldOut: { type: Boolean, attribute: "sold-out" },
  };
  static styles = css`.sold-out h3 { text-decoration: line-through; }`;
  steepButton = createRef();

  constructor() {
    super();
    this.soldOut = false;
  }

  add() {
    this.dispatchEvent(new CustomEvent("tea-add", { detail: this.name, bubbles: true }));
    this.steepButton.value.focus();
  }

  render() {
    return html`<div class=${this.soldOut ? "item sold-out" : "item"}>
      <h3>${this.name}</h3>
      <tea-price .amount=${this.price} currency="EUR"></tea-price>
      <button @click=${this.add} ?disabled=${this.soldOut}>Add to cart</button>
      <button ${ref(this.steepButton)}>Steep</button>
    </div>`;
  }
}

customElements.define("tea-menu-item", TeaMenuItem);
  • Line 24 is an attribute expression: the class is item, or item sold-out.
  • Line 25 is a child expression: the name.
  • Line 26 is a property expression. .amount sets the kit price's amount property.
  • Line 27 has two. @click calls add(), and ?disabled turns the button off for a sold-out tea.
  • Line 28 is an element expression. ref() keeps the Steep button.
  • Lines 18 to 21 are add(). It sends a tea-add event, as lesson 5.3 taught, and moves focus to Steep. Page line 11 puts the tea in the cart.

Sencha shows Price: 4 EUR. Gyokuro is struck through, and its Add to cart is greyed out. Press Sencha's Add to cart. The cart lists Sencha × 1, and focus moves to Sencha's Steep button.

Line 10's static styles strike through the sold-out name. Styles in Lit come later in the stage. Now sort some bindings of your own:

Which binding would you write?
  • The class that gives a sold-out tea its struck-through look
  • An aria-label that says "Add Sencha to the cart"
  • An array of extras for a child component
  • The text of a note box that the user may have typed in
  • disabled on Add to cart while the tea is sold out
  • hidden on the sale banner when there's no sale
  • A click on Add to cart
  • Each input event from the note box
Try it yourself
0 of 8 correct

Put each value in the binding that fits it best.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Common mix-ups

  • "Lit compares a virtual DOM." No. Lit prints the template once. Then it compares each value with the last one it wrote, and writes only the ones that changed.
  • "value=${x} keeps a text box showing x." No. It sets the value attribute, which is only the starting text. Once someone types, only .value=${x} changes what the box shows.
  • "disabled=${false} turns disabled off." No. It writes disabled="false", and the button stays disabled. Write ?disabled=${false}.
  • "A string with tags in a template becomes HTML." No. A child expression writes a string as text. Only unsafeHTML() turns a string into markup.
  • "You can put ${} anywhere in the HTML." No. Expressions go in attribute values and in child content. A changing tag name needs lit/static-html.js.
  • "@click needs this.add.bind(this)." No. In a Lit component, Lit calls a listener function with the component as this. Only an object's handleEvent() gets the object.
  • ".value=${x} checks the box on every render." No. Lit compares x with the last value it wrote, not with the box. If x didn't change, Lit writes nothing.

Practice exercises

Exercise 1 · Warm-upPredict what a child expression shows

Read the page without running it. What does the console print?

<script type="importmap">
  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
</script>
<p id="note"></p>
<script type="module">
  import { html, render } from "lit";
  const note = document.querySelector("#note");
  const tea = "<i>Hojicha</i>";
  render(html`${tea} costs ${5}${undefined} EUR`, note);
  console.log(note.textContent);
</script>

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upPredict what an attribute expression writes

    Read the page without running it. What does the console print?

    <script type="importmap">
      { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
    </script>
    <div id="out"></div>
    <script type="module">
      import { html, nothing, render } from "lit";
      const out = document.querySelector("#out");
      const badge = (kind, note) => html`<span class="badge ${kind}" title=${note}>Tea</span>`;
      render(badge(nothing, null), out);
      console.log(out.querySelector("span").outerHTML);
    </script>

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeTurn on Add to cart for a tea in stock

      Both Add to cart buttons are greyed out, though only Gyokuro is sold out. Fix the tea-menu-item.js tab. What does the console print for Sencha then?

      <script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha"></tea-menu-item><tea-menu-item name="Gyokuro" sold-out></tea-menu-item><script type="module">  import "./tea-menu-item.js";  for (const item of document.querySelectorAll("tea-menu-item")) {    await item.updateComplete;    const button = item.shadowRoot.querySelector("button");    console.log(`${item.name}: disabled is ${button.disabled}`);  }</script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeMake Clear empty the note box

        Type "please" after No sugar, then press Clear. The box keeps your words. Fix the tea-note.js tab, and try again. What does the console print when you press Clear?

        <script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-note></tea-note><script type="module" src="./tea-note.js"></script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeMove focus to Steep after Add to cart

          Press Add to cart. The console shows a TypeError instead of moving focus. Fix the tea-menu-item.js tab. What does the console print then?

          <script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><tea-menu-item></tea-menu-item><script type="module" src="./tea-menu-item.js"></script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeFix a heading with a static tag

            The heading should be an h3, but it looks like plain text, and the console names a strange tag, like <lit$…$>. Fix the tea-heading.js tab. What does the console print then?

            <script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><tea-heading level="3">Sencha</tea-heading><script type="module">  import "./tea-heading.js";  const heading = document.querySelector("tea-heading");  await heading.updateComplete;  console.log(`Heading: <${heading.shadowRoot.firstElementChild.localName}>`);</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              The Lit templates quiz · 8 questionsScore: first tries count
              1. Question 1 of 8In the tea-note component, you type " please" at the end of both boxes, then press Use the house note. What do the boxes show?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                import { LitElement, html } from "lit";
                
                class TeaNote extends LitElement {
                  static properties = { note: {} };
                
                  constructor() {
                    super();
                    this.note = "No sugar";
                  }
                
                  render() {
                    return html`<label>Attribute <input value=${this.note}></label>
                      <label>Property <input .value=${this.note}></label>
                      <button @click=${() => (this.note = "Less sugar")}>Use the house note</button>`;
                  }
                }
                
                customElements.define("tea-note", TeaNote);

                Choose an answer to see the explanation.

              2. Question 2 of 8What does the first line of this boolean page print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                <script type="importmap">
                  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
                </script>
                <div id="out"></div>
                <script type="module">
                  import { html, render } from "lit";
                  const out = document.querySelector("#out");
                  const soldOut = false;
                  render(html`<button disabled=${soldOut}>Plain</button>
                    <button ?disabled=${soldOut}>With ?</button>`, out);
                  for (const button of out.querySelectorAll("button")) {
                    console.log(`${button.textContent}: disabled is ${button.disabled}`);
                  }
                </script>

                Choose an answer to see the explanation.

              3. Question 3 of 8In a Lit component, a template has @click=${this.add}. What is this inside add() when someone clicks?

                Choose an answer to see the explanation.

              4. Question 4 of 8What's the difference between title=${undefined} and title=${nothing} in an attribute binding?

                Choose an answer to see the explanation.

              5. Question 5 of 8A template has @click=${{ handleEvent() { this.cups += 1; } }}. Does clicking change the component's cups?

                Choose an answer to see the explanation.

              6. Question 6 of 8What does this slip page print on its last line?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                <script type="importmap">
                  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
                </script>
                <div id="out"></div>
                <script type="module">
                  import { html, render } from "lit";
                  const out = document.querySelector("#out");
                  const slip = (tea, cups) => html`<p class="slip">${tea}: ${cups} cups</p>`;
                  const first = slip("Sencha", 2);
                  const second = slip("Assam", 2);
                  console.log(`Same strings: ${first.strings === second.strings}`);
                  console.log(`Values: ${second.values.join(", ")}`);
                  render(first, out);
                  const watcher = new MutationObserver(() => {});
                  watcher.observe(out, { subtree: true, childList: true, characterData: true, attributes: true });
                  render(second, out);
                  console.log(`Changes: ${watcher.takeRecords().map((change) => change.type).join(", ")}`);
                </script>

                Choose an answer to see the explanation.

              7. Question 7 of 8In Lit's development build, what happens with html<${tag}>Sencha</${tag}> from the lit package?

                Choose an answer to see the explanation.

              8. Question 8 of 8What happens to <button ${"hello"}>Pour</button>, a plain string in an element expression?

                Choose an answer to see the explanation.

              Key takeaways

              • A Lit template is an html tagged template. Lit prints its HTML once, and then writes only the values that changed.
              • A child expression takes text, numbers, templates, nodes, and arrays. A string always stays text.
              • nothing, null, undefined, and an empty string render no node in a child expression.
              • An attribute expression calls setAttribute(). undefined writes an empty value, and nothing removes the attribute.
              • A dot sets a property. Use it for what a user can change, like a box's text, and for arrays and objects.
              • @ adds an event listener. A listener function gets the component as this.
              • ? adds or removes a boolean attribute. disabled=${false} still disables.
              • An element expression takes a directive, like ref().
              • Tag names, attribute names, and template or textarea content can't hold expressions. Use lit/static-html.js for tags.

              Remember the one-liner.
              The template is a printed slip, and each expression is a blank. Lit fills in only the blanks that changed, in the way the prefix asks.

              Sources

              The facts on this page come from these docs and source files:

              Support data comes from MDN's browser-compat-data.

              Coming next: Conditions and lists in Lit. It shows and hides parts of a template, and renders lists with map and repeat.

              CompleteFrontend Clear concepts. Working examples.