Skip to content

Directives Overview

Directives customize element behavior during hydration. They are defined by attribute names prefixed with : or by property object keys.

Two Syntaxes

All directives can be used two ways:

HTML Attribute Syntax

typescript
html`<div :text=${value}></div>`

Property Object Syntax

typescript
const element = createElement("div");
applyProps(element, { textContent: value });

Both forms resolve through the same directive registry.

How Directives Match

When resolveAttributes runs, it:

  1. Iterates all attributes on each element.
  2. For each attribute, checks the directive registry for a match.
  3. If matched, runs the directive's callback with the element and value.
  4. Removes the directive attribute from the element (so it doesn't appear in the final DOM).

Built-in Directives

SyntaxProperty KeyPurpose
:text=${val}textContentSets text content (safe)
:html=${val}innerHTML / htmlSets inner HTML (unsafe)
class=${val}classManages classes (string, array, object)
class:name=${bool}class:nameToggles a single class
class:[a,b]="${bool}"class:[a,b]Toggles multiple classes at once
class:[a|b]="${bool}"class:[a|b]Toggles between two classes
style=${val}styleSets styles (string or object)
style:prop=${val}style:propSets a single CSS property
attr=${val}attrToggles a native boolean attribute
toggle:attr=${val}toggle:attrToggles any attribute (custom, data-*, etc.)
toggle:[a,b]="${val}"toggle:[a,b]Toggles multiple attributes at once
toggle:attr.opt=${val}toggle:attr.optWith .mirror or .preserve option
:children=${val}childrenReplaces element children
:ref=${obj}_refCaptures element reference
:key=${val}_keySets tracking key for the element
:skip_skipSkips directive processing on subtree
:show=${val}_showToggles display: none
:visible=${val}_visibleToggles visibility: hidden
onEvent=${fn}onEventEvent handler (+ modifiers)
on={...}onObject-map of event handlers

Value Resolution

Directive values are resolved from the template's context. If a value is a reactive reference, some directives set up automatic watchers to update the element when the value changes.

Custom Directives

You can add custom directives for application-specific behaviors:

typescript
Croft.addDirective({
  type: "tooltip",
  match: ":tooltip",
  callback: (element, { value }) => {
    element.setAttribute("title", value);
  },
});

See Custom Directives for details.