Guide
Templates
Real HTML inside TypeScript. The rule that decides what is reactive, and everything you can write in a template.
HTML inside TypeScript
const card = view`
<article class="card">
<h2>${title}</h2>
<p>${() => summary()}</p>
</article>`;view does not exist at runtime: the compiler replaces it with the calls that
build that tree. What it returns is the root element, a plain HTMLElement:
it can be passed to any DOM API.
The attributes are the HTML ones: class, for, onclick, tabindex.
Markup from anywhere can be copied and pasted as is.
The one rule
A closure is reactive. Any other expression is evaluated once.
| You write | What happens |
|---|---|
${count()} |
Inserts the current value. Never looks at it again. |
${() => count()} |
Creates an effect: that text follows the signal. |
class="fixed" |
Static attribute. |
class=${expression} |
Evaluated once, at build time. |
class=${() => …} |
Reactive attribute. |
onclick=${handler} |
DOM listener. Removed by itself on unmount. |
prop:value=${() => …} |
Writes the property, not the attribute. |
class:active=${() => …} |
Adds and removes that class, without touching the others. |
ref=${(node) => …} |
Hands the newly created element to a function. |
The distinction is syntactic: looking at the template tells you what can change, without knowing the types. That is where the easiest trap comes from:
function Metric(props: { value: () => string }) {
return view`<span>${props.value}</span>`; // ✗ renders «() => …»
return view`<span>${() => props.value()}</span>`; // ✓ follows the data
}props.value is a function, but there is no closure written there, and the
rule looks at what is written. A reactive value is passed on by calling it
inside another closure.
Text
A hole inside a tag is always text, escaped:
view`<p>${"<b>not bold</b>"}</p>`; // the text shows as isnull and undefined render an empty string; everything else goes through
String(). To compose nodes you do not use a hole but a
component.
Attributes
A reactive attribute with false, null or undefined disappears, and
with true it stays empty. That is how HTML booleans are expressed: they
either exist or they do not:
view`<button disabled=${() => sending()}>Save</button>`;
// sending() === true → <button disabled>
// sending() === false → <button>javascript: URLs
A URL that reaches href, src, action, formaction or data through a
hole is not written if it is javascript:: in a link it would run on click,
and it almost always comes from outside data.
view`<a href=${payment.url}>Pay</a>`;
// payment.url === "javascript:alert(document.cookie)"
// → href="javascript:throw new Error('Ascua blocked a javascript: URL')"What is left is a harmless URL and a warning in the console, as in React 19.
Written literally in the template —href="javascript:void 0"— it is not
touched: that one was decided by whoever wrote the code. The rest (https:,
mailto:, relative paths) goes through the same. To accept only http(s), it
has to be validated first.
srcdoc
srcdoc is a whole page that runs with the site's origin: through a hole, it
means putting outside HTML into the page. It is only written if the <iframe>
has sandbox written in the template, and not with allow-scripts and
allow-same-origin together, which let it remove its own sandbox:
view`<iframe sandbox srcdoc=${email.html}></iframe>`; // written, no scripts
view`<iframe srcdoc=${email.html}></iframe>`; // srcdoc="" and a console warningAn empty sandbox is the right choice to show someone else's HTML (an email,
a preview): no scripts, no forms and on a separate origin. The same holds in
view!, the Rust path.
Events
view`<input oninput=${(e: Event) => text.set((e.target as HTMLInputElement).value)}>`;on + the name of the DOM event, in lowercase: onclick, oninput,
onsubmit, onkeydown. The handler gets the browser's event and is removed by
itself when the component is released.
Events that bubble up the tree —click, input, change, keydown, pointer
and mouse events, focusin…— are delegated, as in Solid and Svelte: the
handler stays on the node and a single listener per type, on the document,
finds it on the way up. Creating a thousand rows is not two thousand
addEventListener calls. Inside, it behaves like a normal one:
currentTarget is the handler's node and stopPropagation stops the bubbling.
One difference: an event dispatched by hand has to bubble to arrive,
new Event("input", { bubbles: true }). The browser's already do, and so do
the ones from ascua-testing. Those that do not bubble
—scroll, focus, load— go with a plain addEventListener.
Forms: prop:
The value attribute of an <input> is its initial value: it stops being
in charge as soon as the user types. The property is always in charge. That is
why value, checked and selected are written with prop::
const text = signal("");
view`
<form onsubmit=${submit}>
<input prop:value=${() => text()}
oninput=${(e: Event) => text.set((e.target as HTMLInputElement).value)}>
<button type="button" onclick=${() => text.set("")}>Clear</button>
</form>`;With value= instead of prop:value=, the clear button would stop working as
soon as someone typed.
bind:, both ways
The above is so common that it has a shortcut. bind: ties the field to a
signal: what the signal says is shown, and what the user types goes to the
signal.
const name = signal("");
const accepts = signal(false);
const age = signal(30);
view`
<form>
<input bind:value=${name}>
<input type="checkbox" bind:checked=${accepts}>
<input type="number" bind:valueAsNumber=${age}>
<select bind:value=${country}>…</select>
</form>`;You pass it the signal, not a closure. value listens to input,
checked listens to change, and valueAsNumber stores a number (empty is
NaN). Types are checked: binding bind:value to a Signal<number> is an
error.
Classes that come and go: class:
class is an attribute like any other: making it reactive means building the
whole list on every change. For a single class there is class::
view`<li class="row" class:done=${() => task.done()}>…</li>`;row always stays, done appears and disappears, and the CSS scope is not
overwritten.
Keeping a node: ref
let field: HTMLInputElement | undefined;
const form = view`
<form>
<input ref=${(node: HTMLInputElement) => (field = node)}>
</form>`;
field?.focus();The compiler calls ref right after creating the element. It runs on every
build: after a <Show> that rebuilds, the variable points to the new node.
SVG and MathML
const icon = view`
<svg viewBox="0 0 24 24" width="24" height="24">
<circle cx="12" cy="12" r=${() => radius()} class:active=${() => active()}/>
</svg>`;What goes inside <svg> is created in the SVG namespace, and what goes inside
<math> in the MathML one: a <circle> made as an HTML element is not drawn.
Inside <foreignObject> it goes back to HTML. Attributes and class: work the
same; the capitals in viewBox or linearGradient are kept.
A component that returns a piece of drawing for another's <svg> —a <g>, a
<path>— has no <svg> above it to say so. For those, tags that only exist in
SVG are recognized on their own. Those that are also HTML (<a>, <title>,
<style>) cannot know: they go inside a <g>.
To link, plain href; xlink:href is from SVG 1.1 and is not needed.
Limits, and why
- A template has a single root element. That is what lets mounting,
unmounting and hydrating be operations on one node. Where fragments are
needed —the content of a component, a branch of
<Show>— they are there. ${expr}never inserts a node. Telling by the type of the value would be guessing the intent; to compose, a component.<Show>and<For>need a parent to anchor to, because what they produce is a marker inside it. They cannot be the root; in the branch of another<Show>, the parent is that<Show>'s.<!-- … -->comments disappear at compile time, with whatever is inside, holes included: they do not reach the DOM.- Whitespace between tags does not count. A text that is only whitespace
between two elements is dropped, as any HTML minifier does. If a space
matters, it goes inside the text:
<b>one</b>${" "}<b>two</b>.
html, so the editor highlights it
A template is a string, so the editor does not highlight the markup on its
own. The extensions that do —lit-html, es6-string-html— look for the html
tag, and the compiler accepts both names:
const button = html`<button class="big">Hello</button>`; // same as viewWhat comes out of the compiler
view`<p>${() => count()}</p>`;compiles to:
const _$t0 = _$tpl(["p", 0, [""]], [[], [0]], ["p", "#text"],
(r) => { const n0 = r.firstChild; return [r, n0]; }); // at the top, once
const [_n0, _n1] = _$clone(_$t0);
_$bindtxt(_n1, () => count());The fixed part is a template that gets cloned; the text comes in it, empty, and an effect writes the count over it. You can see it for any file in the playground. It is a deliberate property: if the compiler's output cannot be read, the magic came back in through the back door.