Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 38 ยท Templates and Directives

Lit Templates and Bindings

Master Lit templates: the html tag, child expressions, attribute, boolean attribute, property and event bindings with the dot, question mark and at prefixes, and how updates stay fast.

A Lit component describes its UI with a template: a JavaScript template literal tagged with html. Inside it you write plain HTML, and wherever something should change you put an expression ${...}. When the data changes, Lit updates only those expressions, never the whole tree. This lesson covers the five places where an expression can go and the syntax that tells Lit what kind of binding you mean.

Once you can read these five binding types, you can read any Lit template in the wild.

The html tag

JavaScript
import { html } from "lit";

const name = "Ada";
const template = html`<p>Hello, ${name}!</p>`;

html does not return a string or a DOM node. It returns a TemplateResult, a small object that holds the static strings and the dynamic values. Nothing is rendered until you pass the result to render() (a LitElement does this for you after every render() method call).

Rendering a template by hand

Press the button: the line below reports true. That is Lit's core trick: after each render, the <strong> element is the same node as before. Lit did not rebuild the paragraph; it only changed the text inside the expression.

The five places for an expression

flowchart TD
  T["html template"] --> C["Child<br/>${value} between tags"]
  T --> A["Attribute<br/>class=${value}"]
  T --> B["Boolean attribute<br/>?disabled=${flag}"]
  T --> P["Property<br/>.value=${data}"]
  T --> E["Event<br/>@click=${handler}"]

Every Lit binding is one of these five kinds.

1. Child expressions

Between tags, ${value} can hold text, numbers, nested templates, arrays and DOM nodes.

JavaScript
html`<ul>${items.map((i) => html`<li>${i}</li>`)}</ul>`

Text is always escaped, so ${"<b>hi</b>"} appears as literal text and never as bold. That makes Lit safe against cross-site scripting (XSS) by default. The values null, undefined and "" render nothing. The booleans true and false render the words "true" and "false", unlike in some frameworks, so use a conditional instead (see Conditional Rendering).

2. Attribute expressions

In an attribute, name=${value} sets the attribute to the string form of the value. You may mix text and expressions: href="/users/${id}". Quotes are optional around a single expression.

3. Boolean attribute expressions: the ? prefix

Boolean attributes (disabled, hidden, checked, open) work by presence. Writing disabled=${false} would set disabled="false", which is still disabled! The ? prefix fixes that: the attribute is present when the value is truthy and removed when falsy.

4. Property expressions: the . prefix

.value=${x} sets the JavaScript property instead of the attribute. This is how you pass objects, arrays and numbers without turning them into strings, and how you set value on an <input> so that it reflects the current state after the user has typed.

5. Event expressions: the @ prefix

@click=${handler} adds an event listener. Lit binds this to the component for functions defined in the component's class body, so this.count++ works inside methods. The event object is passed as the argument.

All five together

A tiny todo input using every binding

Find each binding type in the code:

  • Property .value=${this.draft} keeps the input's current text in sync with state (and clears it after adding).
  • Event @input and @click update state.
  • Boolean attribute ?disabled=${empty} toggles the button.
  • Attribute class=${...} sets the list item's class.
  • Child ${todo.text} and the mapped list place content.

Note this.todos = [...this.todos, ...]: it assigns a new array rather than pushing into the old one. Lit compares property values with !==, so a mutation of the same array would go unnoticed. Reactive Properties and Internal State explains why in detail.

How the update stays small

Lit splits your template into static strings and dynamic holes at the first render. It builds the DOM once, remembering where each hole is. On later renders it compares each new value with the previous one and touches the DOM only where they differ. The comparison for a given hole is cheap, and no tree is compared. This is why render() can run often without cost.

You can see the pieces yourself: a template result has strings (the static parts) and values.

JavaScript
const t = html`<p>${1} and ${2}</p>`;
console.log(t.strings); // ["<p>", " and ", "</p>"]
console.log(t.values);  // [1, 2]

Two renders that use the same literal in your source share the same strings array object, which is how Lit knows it can reuse the DOM without comparing markup.

Rules for writing templates

  • Expressions go only in the five positions above. You cannot put one in a tag name (<${tag}>) or an attribute name (${attr}="x"), with the exception of static values handled through lit/static-html.js.
  • Templates must be valid HTML fragments. You cannot open a tag in one template and close it in another.
  • Do not build templates by concatenating strings. Always use the html tag; otherwise, you lose escaping and efficiency.
  • A template can be rendered into any container with render(result, container), not only into a LitElement.

Common mistakes

  • Writing disabled=${isDisabled} and being surprised the button stays disabled when isDisabled is false. Use ?disabled.
  • Using the attribute value=${v} on an input and losing the sync after the user types. Use .value.
  • Mutating arrays and objects instead of replacing them.
  • Calling the handler: @click=${this.add()} runs it at render time. Pass the function itself: @click=${this.add}.
  • Putting ${...} inside a <style> or <script> tag within the template. Those positions are not supported; use static styles.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which prefix sets a JavaScript property instead of an attribute?

    .name=${value} assigns element.name = value, which can be any JavaScript value.
  2. 2. What does ?hidden=${false} do?

    The ? prefix adds the attribute when the value is truthy and removes it when falsy.
  3. 3. What does Lit do when an expression's value is the string "<b>hi</b>"?

    Child expressions are inserted as text nodes, so markup in data is never parsed.
  4. 4. Why is @click=${this.add()} a bug?

    Pass the function reference, not the result of calling it.

Summary

  • html tags a template literal and returns a TemplateResult; render() puts it into the DOM.
  • Five binding positions: child ${x}, attribute a=${x}, boolean ?a=${x}, property .a=${x}, event @a=${x}.
  • Text is escaped by default; null and undefined render nothing.
  • Lit builds DOM once and updates only the holes whose values changed.
  • Replace arrays and objects instead of mutating them so changes are detected.

Next: Conditional Rendering