html templates
Markup in a tagged template, turned into real DOM nodes.
html is a tagged template built on
htm. It
returns DOM nodes, not strings, and runs in the browser with no build
step.
Values
html`<p>${text}</p>` // text, set once
html`<p>${() => count.value}</p>` // text, kept up to date
html`<p>${html`<b>nested</b>`}</p>` // nodes
Attributes and events
html`
<input
type="text"
class=${() => (invalid.value ? 'invalid' : '')}
disabled=${() => busy.value}
onInput=${(e) => (name.value = e.currentTarget.value)} />
`
A function value binds the attribute. An on attribute with
a function adds a listener. ref captures the element, see
Refs and forms.
Components
A component class goes in the tag name position, closed with
</${Card}> or self closed with
<${Card} />.
SVG
Write SVG in a template as you would in HTML. svg,
circle, path and the other SVG tags are
created in the SVG namespace, and bindings work on their attributes.
a, title, style and
script exist in HTML and SVG and are created as HTML.
Inside an SVG, give them xmlns="http://www.w3.org/2000/svg".
Pitfalls
- Close void elements:
<input />,<br />,<img />. Without the slash, the parser treats the rest of the template as their children and rendering fails. ${this.count.value}renders once. Bind${() => this.count.value}.- A function child that returns markup, such as
${() => ok ? html`...` : null}, renders an empty text node. UseShow. .map()over a signal array renders once. UseFor.
Hyperscript
h(tag, props, ...children) is the function under
html, for code that builds nodes without a template.