Skip to content

Directives

WebJs ships the lit-html directives under their Lit names and with Lit's behaviour, so code written from Lit muscle memory works as written. That includes the attribute helpers classMap, styleMap, and ifDefined, the nothing / noChange sentinels, the when / choose / map / join / range helpers, and static expressions from @webjsdev/core/static-html. The implementations live in packages/core/src/directives.js and the renderers (render-server/walk.js, render-client/parts.js). Lit's import paths map one to one: lit/directives/*.js is @webjsdev/core/directives, lit/static-html.js is @webjsdev/core/static-html.

import { html, svg, mathml, repeat, nothing, noChange, isServer } from '@webjsdev/core';
import {
  classMap, styleMap, ifDefined, unsafeHTML, unsafeSVG, unsafeMathML, live,
  keyed, guard, templateContent, ref, createRef,
  cache, until, asyncAppend, asyncReplace,
  when, choose, map, join, range, watch,
} from '@webjsdev/core/directives';
import { literal, unsafeStatic, html as staticHtml } from '@webjsdev/core/static-html';

repeat(items, keyFn, templateFn)

Keyed list reconciliation. Without it, an array updates position by position: the DOM for item N is reused for whatever is now at index N, so on a reorder or an insert, focus, scroll position and component state stay with the position rather than the item. repeat() moves each item's DOM with its key.

html`<ul>
  ${repeat(
    items,
    (item) => item.id,
    (item) => html`<li>${item.name}</li>`
  )}
</ul>`;

Use for any list where items can be added, removed, or reordered and you need to preserve DOM identity (animated lists, forms with inputs, draggable items). For static lists, plain ${items.map(...)} works.

Lit's two-argument form, repeat(items, (item, i) => html`...`), works too. With no key function each item is keyed by its index, so it updates positionally like a plain array; pass a key function whenever DOM identity has to follow the data.

watch(signal)

Binds one hole to a signal: when the signal changes, only that text node or attribute updates, without re-running the host's render() or its lifecycle hooks. A bare ${signal} in a hole does the same thing, as in Lit's signals package; watch() is the explicit spelling, also exported from @webjsdev/core/signals.

html`<p>Unread: ${watch(unread)}</p>`;

unsafeHTML(htmlString)

Renders a raw HTML string without escaping. The only way to inject pre-built HTML (CMS content, markdown output) into a template.

html`<article>${unsafeHTML(markdownToHtml(post.body))}</article>`;

As in Lit, it takes a string: nothing, null or undefined render nothing, noChange keeps what is there, any other value throws, and the same string on a re-render keeps the existing nodes.

unsafeSVG(svgString) / unsafeMathML(mathString)

The SVG and MathML twins of unsafeHTML. The client parses the string in that namespace, so a <circle> or a <mi> becomes a real SVG or MathML element; the server emits the markup verbatim. Put the hole inside the <svg> or <math> element. The same rule as unsafeHTML applies: never pass user input.

html`<svg viewBox="0 0 24 24">${unsafeSVG(iconPaths)}</svg>`;

Security: NEVER use with user-supplied input. This is an XSS vector.

live(value)

Dirty-checks against the live DOM value instead of the last rendered value. Solves the input desync problem where the user types between renders.

html`<input .value=${live(this.query.get())}
       @input=${(e) => this.query.set(e.target.value)}>`;

Client-only behaviour. The server renders one shot, so there is no prior value to dirty-check against and live() is fully transparent there, resolving to the value it wraps in every hole position (a child, a plain attribute, a ?bool, a .prop). A falsy boolean stays absent, so ?open=${live(false)} serves the same bytes as ?open=${false}.

keyed(key, template)

Wrap a template with a key. When the key changes between renders, the renderer discards the prior DOM and creates fresh. Useful for forcing a remount when the logical identity of the rendered content changes.

html`${keyed(this.userId, html`<edit-form .user=${this.user}></edit-form>`)}`;

guard(deps, fn)

Memoize a sub-template by its dependencies. The client renderer skips re-evaluating fn() when the deps array is shallow-equal to the prior call. On the server (one-shot render) fn() is always invoked.

html`<header>
  ${guard([this.title], () => html`<h1>${this.title}</h1>`)}
</header>`;

templateContent(tpl)

Render the content of a native <template> element. The content is cloned on the client; on the server, its innerHTML is emitted verbatim. The HTML inside the template is trusted (not escaped).

const tpl = document.querySelector('#my-tpl');
html`<div>${templateContent(tpl)}</div>`;

ref(refOrCallback) + createRef()

Bind a Ref object or callback to the element at this position. The Ref's value is populated after the first client-side render. SSR is a no-op (no DOM yet).

class MyForm extends WebComponent {
  _input = createRef();
  render() { return html`<input ${ref(this._input)}>`; }
  firstUpdated() { this._input.value?.focus(); }
}

Pass a callback instead of a Ref object to receive the element directly: ${ref((el) => this._captureEl(el))}. A method passed as the callback is called with the rendering component as this, as in Lit, so ${ref(this.captureEl)} works unbound.

cache(value)

Retain detached DOM when toggling between sub-templates. When the inner value's template strings match a previously-rendered template at this position, the renderer re-attaches the stashed nodes and reconciles values instead of creating fresh DOM. Preserves input state, scroll position, and focus across "tab"-style toggles.

render() {
  return html`
    <nav>
      <button @click=${() => this.tab = 'a'}>A</button>
      <button @click=${() => this.tab = 'b'}>B</button>
    </nav>
    ${cache(this.tab === 'a' ? html`<panel-a></panel-a>` : html`<panel-b></panel-b>`)}
  `;
}

On the server, cache is a pass-through (one-shot render, no DOM to cache).

until(...args)

Render the highest-priority resolved candidate. Priority is left-to-right: args[0] is highest. The highest-priority synchronous candidate renders immediately; higher-priority Promises that later resolve replace the rendered value. Lower-priority Promises are ignored once a higher-priority candidate is in place.

html`<div>${until(this.dataPromise, html`<p>Loading…</p>`)}</div>`;

As in Lit, it works at every binding position, not only as a child: src=${until(this.avatar, '/placeholder.png')} writes the placeholder now and the resolved url later, and the same holds inside an interpolated attribute and for .prop, ?bool and @event bindings. guard, keyed and cache unwrap in those positions too.

When the marker is torn down (a re-render replaces the directive), in-flight Promise tracking is aborted so late resolves cannot overwrite newer DOM. On the server, until awaits Promise.race when all candidates are Promises, or renders the highest-priority synchronous candidate.

For component-scoped async data with full pending/error states, prefer the Task controller from @webjsdev/core/task.

asyncAppend(iterable, mapper?) / asyncReplace(iterable, mapper?)

Stream values from an AsyncIterable. Each yielded value is mapped (optional) and rendered as a node group. asyncAppend accumulates the rendered groups before the marker; asyncReplace swaps out the previous output each yield. Iteration aborts when the directive is replaced (so leaked iterators don't hold references to detached DOM).

async function* logTail() {
  for await (const line of socket) yield line;
}

html`<ul>${asyncAppend(logTail(), (line, i) => html`<li>${i}: ${line}</li>`)}</ul>`;

On the server, both directives render empty (no iteration on a one-shot render). For page-level streaming, prefer Suspense({ fallback, children }).

classMap(classes) / styleMap(styles) / ifDefined(value)

The same helpers as Lit. classMap toggles the classes whose value is truthy and keeps any static classes written beside it; styleMap sets inline style properties (camelCase or --custom names) and drops a nullish one; ifDefined omits the attribute when the value is null or undefined. All three render on the server too, so the first paint carries the classes and styles.

html`<div class="card ${classMap({ active: isActive, error: hasError })}">`;
html`<div style=${styleMap({ color: c, fontSize: size, '--gap': gap })}>`;
html`<img src=${ifDefined(src)}>`;

Lit's template rules

The renderer follows lit-html's own test suite, ported into WebJs. A few rules from it that code relies on:

  • A DOM node in a child hole is inserted as that node, and an array or iterable of nodes inserts each one. An empty string renders no node.
  • A hole inside <script>, <style>, <textarea> or <title> renders as text, on the server and the client alike.
  • An unquoted attribute value may mix text and holes (class=card-${variant}, href=${base}/${slug}). It is one value running to the next space or >, and the server writes it quoted and escaped, so a value holding a space or a > cannot add an attribute.
  • render(value, container) returns Lit's root part: setConnected(false) disconnects the async directives that render created and setConnected(true) reconnects them.
  • A template result is only rendered when it came from html, svg or mathml. An object that only looks like one (JSON carrying the template shape) is refused, as Lit refuses it, so data can never be rendered as markup.

nothing / noChange

Lit's sentinels. nothing renders nothing in a child position, removes an attribute (the whole attribute when it is one piece of an interpolated value), and assigns undefined to a property. noChange leaves the last committed value in place. Like Lit, a plain attribute hole renders null and undefined as an EMPTY attribute and a boolean as text, so write attr=${value ?? nothing} to omit one and ?checked=${on} for a boolean attribute.

html`<a href=${url} aria-current=${active ? 'page' : nothing}>`;
html`${error ? html`<p role="alert">${error}</p>` : nothing}`;

when / choose / map / join / range

Lit's control-flow helpers, with Lit's signatures. They are plain functions, so they behave the same on the server and the client. when(condition, trueCase, falseCase?) calls the case it picks with the condition value; choose(value, cases, defaultCase?) matches keys with ===; map, join, and range return generators.

html`
  ${when(this.user, (u) => html`<p>Hi ${u.name}</p>`, () => html`<a href="/login">Sign in</a>`)}
  ${choose(this.tab, [
    ['home', () => html`<home-tab></home-tab>`],
    ['about', () => html`<about-tab></about-tab>`],
  ], () => html`<p>Not found</p>`)}
  <ol>${map(range(3), (i) => html`<li>Step ${i + 1}</li>`)}</ol>
  <p>${join(this.tags, html`<span>, </span>`)}</p>
`;

A ternary, a switch, and Array methods work just as well; pick whichever reads better.

Any iterable renders like an array

A child hole accepts any iterable, not only an array: a generator (which is what map, join, and range return), a Set, a Map's values(). Each item renders in order, exactly as the items of an array do. A string is the one exception: it renders as text, never character by character. The same holds for a value passed straight to render(value, container), as in Lit: render(map(items, fn), el) renders the list.

svg / mathml template tags

An html template is parsed as HTML on the client, so a fragment built for the inside of an <svg> or <math> element (a <rect> per data point, a <mi> a helper returns) needs the svg or mathml tag from @webjsdev/core. The client then parses it in that namespace. The server renders all three tags alike. A whole <svg> element still belongs in html.

const bar = (v, i) => svg`<rect x=${i * 10} height=${v} width="8"></rect>`;
html`<svg>${values.map(bar)}</svg>`;

Static expressions (@webjsdev/core/static-html)

Lit's lit/static-html.js under a WebJs path. A static value is spliced into the template's strings before it renders, so it can stand where an ordinary hole cannot, most often a tag name chosen at runtime. literal takes a template literal whose own holes must be static values; unsafeStatic trusts any string as markup, so never pass user input to it. The merged strings are cached by their text, so the same static shape reuses one template and updates in place.

import { html, literal, unsafeStatic } from '@webjsdev/core/static-html';

const tag = literal`my-button`;
html`<${tag} label="Save"></${tag}>`;
html`<${unsafeStatic(level)}>Title</${unsafeStatic(level)}>`;

withStatic(tag) wraps any other template tag the same way, and svg / mathml come pre-wrapped.

Writing your own directive

Lit's directive authoring API, from @webjsdev/core/directive (Lit's lit/directive.js) and @webjsdev/core/async-directive (Lit's lit/async-directive.js). Subclass Directive, implement render(), and wrap the class with directive(). The constructor receives the part info (type is a PartType; an attribute part also has name, tagName, and, when interpolated, its static strings), so a directive can refuse a position it does not support.

import { directive, Directive, PartType } from '@webjsdev/core/directive';

class Uppercase extends Directive {
  constructor(partInfo) {
    super(partInfo);
    if (partInfo.type !== PartType.CHILD) throw new Error('uppercase() only works in a child position');
  }
  render(text) {
    return String(text).toUpperCase();
  }
}
export const uppercase = directive(Uppercase);

html`<p>${uppercase(name)}</p>`;

The lifecycle is Lit's. One instance lives per part for as long as the same directive class renders there (per piece of an interpolated attribute); a different class or a plain value replaces it. In the browser every render calls update(part, values), whose default forwards to render(...values); override it for DOM access (part.element for an element or attribute part, part.parentNode for a child part, part.options.host for the component). On the server only render() runs, since there is no DOM. Whatever comes back renders like any other value, so a directive may return a template, nothing, noChange, or another directive. Inside an array item a directive has no part of its own, so it renders through render() each time.

An AsyncDirective can also push a value outside a render with setValue(), and hears disconnected() when its component leaves the document (or its part is torn down) and reconnected() when the component comes back. Release subscriptions in the first and restore them in the second.

import { AsyncDirective, directive } from '@webjsdev/core/async-directive';

class Clock extends AsyncDirective {
  render() {
    this.start();
    return new Date().toLocaleTimeString();
  }
  start() {
    clearInterval(this.timer);
    this.timer = setInterval(() => this.setValue(new Date().toLocaleTimeString()), 1000);
  }
  disconnected() { clearInterval(this.timer); }
  reconnected() { this.start(); }
}
export const clock = directive(Clock);

isServer

Lit's flag, from @webjsdev/core: true during SSR on Node or Bun, false in a browser. Use it to guard browser-only work in code that runs on both sides (a constructor, render(), willUpdate(), a controller's hostUpdate()).

if (!isServer) this.width = window.innerWidth;