[]previous and next page

template

Turns a static HTML string into a factory of fresh DOM copies: the helper compiled JSX uses for the static part of every element tree.

Turns a static HTML string into a factory of fresh DOM copies: the helper compiled JSX uses for the static part of every element tree. The markup is parsed on the first call and cloned on every call after that, so creating a template touches no DOM. Each call draws the next hydration key; during hydrate() it returns the server's element for that key instead of a clone.

Import#

ts
import { template } from "@shadow-js/web";

Signature#

ts
function template(html: string, flags = 0): () => Node

Parameters#

Name Description
html Markup of one or more sibling roots. It is trusted: it is parsed as written, never escaped.
flags Bit set: 1 parses the content inside <svg> so it gets the SVG namespace, 2 does the same for MathML, 4 clones with document.importNode (needed for custom elements). Default: 0 (HTML, cloneNode).

Returns#

A function that returns a new, detached node on every call: the root itself when the markup has one root, otherwise a DocumentFragment holding the roots.

Examples#

ts
import { template } from "@shadow-js/web";

const makeCard = template(`<div class="card"><h2></h2></div>`);
const card = makeCard() as HTMLDivElement;
(card.firstChild as HTMLElement).textContent = "Title";
document.body.append(card);