liveBook · Manning

HTML template element

As explained in Web Component Development with Modern Libraries and Tooling

An HTML element containing reusable markup that is not rendered until its contents are cloned into a document.

A template element holds reusable markup without rendering it immediately. For a web component with substantial HTML, define its shared structure once, then clone its content into each instance’s shadow root. section 1.2 section 4.2.3

A radio group from one template

A radio-group component starts with a template containing its CSS, a fieldset, a legend, slots, and an empty container for buttons. Its render method clones `template.content`, fills in the legend and radio buttons, then calls `shadowRoot.replaceChildren(dom)`. Each instance gets a populated copy rather than rebuilding the entire structure from scratch. section 3.10

// Outside the web component class ...
const template = document.createElement("template");
template.innerHTML = html`...add HTML here`;

// In a method of the web component class ...
const element = template.content.cloneNode(true);
this.shadowRoot.replaceChildren(element);

A compact four-step pattern: create a template, assign its HTML, clone its content, and replace the shadow root’s children with the clone. section 4.2.3

Cloning is useful for an initial render, but an update need not replace the whole shadow DOM. If only a value changes, updating existing elements can be more efficient. Vanilla web components handle this rendering work directly; libraries can reduce the boilerplate. section 3.10 section 3.0

How Web Component Development with Modern Libraries and Tooling covers it

How deep it goes
Works through template creation, HTML assignment, cloning, and shadow-root insertion, including a populated radio-group render method.
Examples
Uses a radio-group template with a fieldset and slots, plus a sortable-table template with table headings and a body.
What it assumes
Introduces template creation step by step while using JavaScript DOM methods and a web component with a shadow root.
What you can do after
Build it from scratch by cloning template content, populating the copy, and placing it in a component’s shadow root.
How it connects
Connects HTML Templates with custom elements, Shadow DOM, slots, and DOM updates.

Also explained in

Compare how 3 books explain HTML template element →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Component Development with Modern Libraries and Tooling. The section links point to the parts of the book it draws on.