Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 38 ยท Templates and Directives

Template Composition and Reuse

Break big Lit templates into small pieces: helper render methods, template functions, child components, SVG and MathML templates, static html and render() into any container.

A component's render() method grows with the UI. Without structure it turns into a hundred lines of nested markup that nobody wants to touch. Because Lit templates are plain JavaScript values, you split them the same way you split any code: into small functions that return templates. This lesson shows the ways to compose templates, when to promote a piece to its own component, and how to render SVG, MathML and templates outside a component.

Templates are values

A TemplateResult is an ordinary value. You can store it in a variable, return it from a function, put it in an array, or pass it as an argument. Wherever a child expression accepts a value, it accepts a template.

Helper methods and template functions

render() now reads like an outline. The helper money lives outside the class, so any component can import it. Each renderX() method returns a template and has access to this. Notice that a template function can return a fragment (<tfoot> in a template of its own), as long as the fragment is valid HTML when rendered in place.

flowchart TD
  R["render()"] --> H["renderHeader()"]
  R --> T["table"]
  T --> Rows["items.map(renderRow)"]
  Rows --> M["money()"]
  T --> F["renderFooter()"]
  F --> M

One render method, several small template functions.

Methods, functions or components?

You have three levels of reuse. Choose the lightest one that works.

Tool Own state Own styles Own events and lifecycle Use when
Template function No, only arguments No, uses the caller's styles No A fragment used in one or a few components
Render method Reads this Component's styles Handlers on the same component Splitting a large render()
Child component Yes Yes, scoped Yes Reuse across the app, own state, or a clear public API

A rule of thumb: if a piece needs its own properties, styles or events, make it a component. If it is only markup that you want to name, use a function. Components cost a bit more (an element, a shadow root), so a row in a list of 1,000 may be better as a function than as 1,000 elements.

Passing templates as arguments

Functions that accept templates give you layout components without slots. A "card" function receives pieces and places them:

JavaScript
const card = (title, body) => html`
  <section class="card">
    <h3>${title}</h3>
    <div>${body}</div>
  </section>`;

html`${card("Profile", html`<user-form></user-form>`)}`

For real component APIs, slots (see Slots and Component Composition in Lit) are the standard: they let the page author provide the pieces in HTML.

SVG and MathML templates

HTML templates parse their markup as HTML, so <circle> inside html ends up as an unknown HTML element and does not draw. For SVG fragments, use the svg tag. An svg template is only valid inside an <svg> element that is itself in an html template.

SVG with the svg tag

Each bar is a small svg template returned from a method. Bindings work exactly as in HTML templates, so the bar height, position and color all come from data. Lit also offers a mathml tag for MathML fragments, with the same rule: use it for content inside a <math> element.

Rendering outside a component

render(template, container) is the function a LitElement uses internally. You can call it directly to put a Lit template into any DOM node, for example to add Lit to an existing page piece by piece:

JavaScript
import { html, render } from "lit";

render(html`<h1>Hello ${name}</h1>`, document.getElementById("app"));

Calling render again with the same container updates it instead of replacing it, which gives you the same efficient updates as in a component. This makes Lit templates a good small-scale replacement for innerHTML in plain scripts.

Static values and dynamic tag names

Normal bindings cannot change a tag name: <${tag}> is not allowed, because the template structure must stay the same between renders. When you really need a dynamic tag (for example, a heading level from a property), use the static html helpers, which build a new template whenever the static value changes:

JavaScript
import { html, literal } from "lit/static-html.js";

const tag = literal`h${this.level}`;  // only trusted values; literal is an escape hatch
return html`<${tag}>Title</${tag}>`;

literal values must come from your own code, never from user input, since they become part of the template's markup. Each distinct value creates a distinct template, so keep the set small.

noChange and fine control

Besides nothing, Lit has a second sentinel, noChange, mainly for writing directives: returning it from a directive means "leave the DOM as it is". You rarely use it in everyday templates. Keep it in mind when you read directive source code.

Organizing template code

  • Put shared template functions in a module (templates.js) and import them.
  • Keep render() free of logic: compute derived values at the top, then return the template.
  • Prefer small named methods over deeply nested ternaries.
  • Avoid creating functions inside loops when a method will do; inline arrow functions are fine for short handlers, though.
  • Name template helpers renderX so they are easy to find.

Common mistakes

  • Using the html tag for SVG children. Use svg inside an <svg> element.
  • Returning half-open tags from a helper (an opening <div> in one and the closing in another). Every template must be balanced.
  • Turning every small piece into a custom element, then paying for thousands of shadow roots.
  • Building dynamic tag names with string concatenation. Use static-html instead.
  • Calling render() with a different container each time and expecting updates to be applied.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which is the lightest way to reuse markup with no state of its own?

    Template functions are plain JavaScript and add no element or shadow root.
  2. 2. When must you use the svg tag instead of html?

    Fragments that go inside an <svg> element must be parsed as SVG, so they use the svg tag.
  3. 3. What does calling render(template, container) twice with the same container do?

    Lit remembers the previous render for that container and only updates changed expressions.
  4. 4. When should a piece of UI become a custom element?

    Components are worth their overhead when encapsulation and an API matter; otherwise a template function is enough.

Summary

  • Templates are values: return them from functions, store them, nest them.
  • Split large render() methods into renderX() helpers and shared template functions.
  • Choose the lightest reuse tool: function, render method, then component.
  • Use svg and mathml for fragments inside those elements; render() works in any container.
  • Dynamic tag names need lit/static-html.js with trusted literal values.

Next: Reactive Properties and Internal State