Templates
The full template grammar: expressions, functions, conditionals, loops, slots, snippets, and refs.
Everything inside a <puzzle-view> block is a Puzzle template. It's HTML plus a small set of directives that read from the model your data() returns. This page is the complete grammar, with a cheat sheet at the bottom.
Interpolation
Single braces evaluate an expression against the model and render the result as text:
<span>{ todo.text }</span>A template expression is JavaScript's expression syntax, from a closed table. It reads fields and literals, combines them with JavaScript's operators, and calls functions and methods from a fixed list. Model getters (computed properties defined on a PuzzleModel) read like plain fields:
<div>{ activeTodos.length }</div>
<button @click={ clearCompleted }>Clear ({ completedTodos.length })</button>
<p>{ currency(price * quantity) }</p>
<p>{ nickname ?? name }</p>
<p>{ `${user.first} ${user.last}` }</p>
<small>{ user.fullName }</small>What an expression can hold
- Literals. Numbers, strings, template literals (
`${first} ${last}`),trueandfalse,nullandundefined, lists ([price, qty]), and objects ({ count: n }). An expression can't start with an object literal, so its place is a function argument:{ t('cart.count', { count: n }) }. - Paths.
a.b,a?.b, anda[expr]. Reading through a missing value never throws:{ user.address.city }prints nothing whileaddressis missing, and a method call on a missing value ({ note.trim() }) prints nothing too. Writing?.yourself is legal, just unnecessary. - Operators. Arithmetic (
+ - * / %), comparisons (< <= > >=), equality (== != === !==),&& || !, the ternary, and??, each meaning what it means in JavaScript. Test for a missing value withx == null. An empty list is truthy, as in JavaScript, so testitems.lengthwhen you mean "has items". - A fallback is
??, never||.{ count ?? 'none' }replaces only a missing value, so a count of0still prints, where||would swallow0and''. Mixing??with&&or||needs parentheses. .lengthis the count of a list's items or a string's UTF-16 units, as in JavaScript..sizeisn't special: it reads a field namedsize, likefile.size.- Arrow functions go only in call arguments, with an expression body:
todos.filter(t => !t.done),rows.toSorted((a, b) => a.rank - b.rank). A callback receives the item and its index.
Calls come in three kinds, and nothing else is callable. A function from the library is called by its bare name ({ currency(price) }). A method comes from the table below, called on a string, a list, or a number ({ name.trim() }, { tags.join(', ') }, { items.at(-1).title }). A global comes from a short list ({ Math.max(0, remaining) }, href="/search?q={ encodeURIComponent(query) }").
| Kind | Names |
|---|---|
| String methods | atcharAtincludesstartsWithendsWithindexOflastIndexOfslicesubstringsplitreplacereplaceAlltrimtrimStarttrimEndtoUpperCasetoLowerCasepadStartpadEndrepeatconcat |
| List methods | atincludesindexOflastIndexOfsliceconcatjoinflatfindfindIndexfindLastfiltermapsomeeveryreducetoSortedtoReversed |
| Number methods | toFixedtoString |
| Math | Math.absMath.ceilMath.floorMath.roundMath.truncMath.maxMath.minMath.signMath.powMath.sqrtMath.PIMath.E |
| Conversion | NumberStringBooleanparseIntparseFloatisNaNisFinite |
| URIs | encodeURIComponentdecodeURIComponentencodeURIdecodeURI |
| Lists and objects | Array.isArrayObject.keysObject.valuesObject.entries |
Each method means what it means in JavaScript, and none of them mutates its receiver: there's no push, sort, reverse, or splice, so use concat, toSorted, and toReversed. There's no Date, JSON, or new, and window, document, and globalThis are out of reach: read what you need from the browser in data() and return it. Any other name, location and localStorage included, reads the data() field of that name.
Everything outside the table is a compile error that names the fix, at the exact line and column: bitwise operators, **, in, instanceof, typeof, void, delete, new, the comma operator, assignment, ++ and --, regex literals, spread, comments inside an expression, await, and any method not in the table. When a value needs more logic than one expression holds, compute it in data() and read that field.
<!-- Error: `.sort()` is not available in template expressions — use `toSorted()` -->
{#for post in posts.sort((a, b) => b.date - a.date)} … {/for}
<!-- Error: `**` is not available in template expressions — use `Math.pow(a, b)` -->
<p>{ side ** 2 }</p>
<!-- Do -->
{#for post in posts.toSorted((a, b) => b.date - a.date)} … {/for}
<p>{ Math.pow(side, 2) }</p>Names, this, and event
The names in scope are your data() fields, loop variables, snippet parameters, and arrow parameters. A name you import or declare in <script> is not reachable from the template (the compiler warns when a template reads an imported name), so compute values in data() and render the result.
- A template never reaches the view instance.
thisis not available in any template expression, and writing it is a compile error that says to return the value fromdata()(a getter or a computed field) or use a function for a display transform. Every value a template shows comes throughdata()and the model. - Handlers are the one door into your view's JavaScript.
@click={ save }names a handler, and@click={ save(item.id, items.length - 1) }calls one with arguments written in the same expression language, evaluated when the event fires. - Inside a handler,
eventis the DOM event. Outside handlers it can be an ordinary data field. Reading it as data and also using the free DOM event in a handler in the same template is a compile error: rename the data field or prop. A chain rooted at the DOM event is unrestricted:@input={ rename(event.target.value) }. Callevent.preventDefault()inside the handler, or use the:preventmodifier. See Events & Binding.
How values print
One rule covers every text position, in the browser and in prerendered pages alike:
- Missing values print nothing.
nullandundefinednever render as words, and anundefinedlogs a development warning naming the expression (it usually means a mistyped field). - Numbers print as JavaScript prints them, except
NaNand ±Infinity, which print nothing.0andfalsestill render. - A list prints its items joined with a comma.
- Any other object prints nothing, with a development warning. That includes a
Date, aURL, or anything with its owntoString: format it ({ date(post.publishedAt) }) or print one of its fields.
Functions
A function transforms a value for display. Call it the way JavaScript calls a function, with the value first and any arguments after it. Calls nest, and the inner call runs first:
{ datetime(todo.createdAt, 'short') }
{ capitalize(text.trim()) }
{ currency(price, '€', 0) }
{ truncate(capitalize(title), 40) }
{ pluralize(comments.length, 'comment') }A call is an ordinary expression, so it goes anywhere a value goes: text, quoted and brace-only attributes, component props, marker arguments, conditions, and loop headers:
<span title={ currency(price) }>…</span>
<a href="{ link('/posts/' + post.slug) }">{ post.title }</a>
<Card label={ truncate(name, 20) } />
{#if post.title.startsWith('Draft')} <span class="badge">Draft</span> {/if}- A bare call names a function; a bare name reads
data(). The two never resolve to each other, so a data field is never callable and never shadows a function. Calling a template binding (a loop variable, a snippet parameter, or an arrow parameter) is a compile error. - There's no pipe. A
|in an expression is a compile error at the|that says to writecurrency(price). There's no bitwise OR either, and||is logical OR.
The function library
The library is the 19 standard functions shared with Magic Spells Sites, with the same names, arguments, and meaning in both, plus two PuzzleKit-only functions: link and timeago. PuzzleKit is the app framework these docs cover; those two sit outside the shared standard set, but they run everywhere a Puzzle app renders, prerendered pages included. Every one of them is below:
<!-- Numbers -->
{ round(rating, 1) } <!-- 4.25 → 4.3 -->
{ currency(price) } <!-- $19.99 -->
{ currency(price, '€', 0) } <!-- €20 -->
{ currency(price * qty) } <!-- arithmetic goes inside the call -->
{ percentage(12.5, 1) } <!-- 12.5% -->
{ percentage(ratio * 100) } <!-- a ratio of 0.42 prints 42% -->
{ number_with_delimiter(count) } <!-- 1,234,567 in en-US -->
{ compact_number(followers) } <!-- 1.2K, 45K, 3.4M -->
<!-- Text -->
{ pluralize(comments.length, 'comment') } <!-- 1 comment, 3 comments -->
{ pluralize(people.length, 'person', 'people') } <!-- 1 person, 2 people -->
{ capitalize(name) } <!-- first character only -->
{ truncate(post.body, 100) } <!-- at most 100 characters, ellipsis included -->
{ strip_html(bio) } <!-- tags removed, text kept -->
{ strip_newlines(address) } <!-- line breaks removed -->
<!-- Markup: see Rendering HTML below -->
{ escape(note) } <!-- an identity: text is always escaped -->
{ raw(post.bodyHtml) } <!-- sanitized HTML -->
{ newline_to_br(note) } <!-- line breaks become <br> -->
<!-- Values -->
{ json(settings) } <!-- JSON with sorted keys -->
<!-- Dates: short, medium, long, iso -->
{ date(post.publishedAt) } <!-- Sep 24, 2026 -->
{ date(post.publishedAt, 'short') } <!-- 9/24/26 -->
{ date(post.publishedAt, 'long') } <!-- September 24, 2026 -->
{ date(post.publishedAt, 'iso') } <!-- 2026-09-24 -->
{ time(post.publishedAt) } <!-- 3:04 PM -->
{ datetime(post.publishedAt) } <!-- Sep 24, 2026, 3:04 PM -->
{ datetime(post.publishedAt, 'short') } <!-- 9/24/26, 3:04 PM -->
{ time(in_timezone(meeting.startsAt, 'Europe/Paris')) } <!-- the wall clock in Paris -->
<!-- Translations, once they're configured -->
{ t('cart.title') } <!-- Your cart -->
{ t('cart.count', { count: items.length }) } <!-- 3 items -->
<!-- PuzzleKit-only -->
{ timeago(post.publishedAt) } <!-- 2 hours ago -->
<a href="{ link('/posts/' + post.id) }">…</a> <!-- a router-correct href -->A few behaviors worth knowing:
pluralizeprints the count and the word.{ pluralize(n, 'comment') }renders3 comments, with the count in the viewer's locale. Pass a third argument for an irregular plural.capitalizetouches only the first character.iPhonebecomesIPhone. To lowercase the rest, writecapitalize(name.toLowerCase()).- Numbers follow the viewer's locale.
number_with_delimiter,compact_number,pluralize's count, and the dates render in the viewer's locale (or the active locale, when translations are configured).currencyis locale-independent: it groups thousands and puts the sign first, as in-$1,234.50. Prerendering uses the build machine's locale (LANG or LC_ALL) and time zone (TZ), with the default locale taking precedence when translations are configured; the browser then renders in the viewer's zone and selected locale. percentagetakes the number as written.percentage(12.5, 1)is12.5%, and with no places it rounds to a whole percent. For a ratio, write{ percentage(ratio * 100) }.roundrounds half away from zero and accepts negative places (round(1250, -2)is1300). It returns a number, and the arithmetic goes inside the call:{ round(total / count, 1) }.- The number functions print nothing for a missing value,
NaN, orInfinity. An unset price prints nothing rather than$0.00, and{ currency(total / count) }over an empty list prints nothing rather than garbage. truncatecounts code points, so an emoji is one character to it (where.lengthcounts UTF-16 units). Its result never exceeds the length, ellipsis included.escapeis an identity. A text interpolation already escapes, so the page shows the value's characters, never a double-escaped<b>.jsonsorts object keys, and a missing value,NaN, orInfinitybecomesnull.
Dates
date, time, and datetime take a value, an optional preset ('short', 'medium', 'long', or 'iso'), and an optional locale. The examples below use US English and a value falling on September 24, 2026 at 3:04 PM in the viewer's zone. Each has its own default:
date(v)is the medium date,Sep 24, 2026.date(v, 'short')is date-only too:9/24/26.time(v)is the short time,3:04 PM.datetime(v)is the medium date with the short time,Sep 24, 2026, 3:04 PM. Usedatetime(v, 'short')for a short stamp,9/24/26, 3:04 PM.'iso'is RFC 3339 in the viewer's time zone. A bareYYYY-MM-DDstring is a calendar date, so it displays as written in every time zone.
A string-literal preset the standard functions don't know (time(at, 'shrot')) is a compile warning that names the valid presets. At run time an unknown preset renders the default, with a development error.
in_timezone(v, 'America/New_York') returns a date for the others to present: { time(in_timezone(meeting.startsAt, zone)) }. A bare date prints nothing, so always format it. timeago(v) renders relative time (2 hours ago), read from the clock when it renders. A template can't construct a date (there's no new and no Date) and a date has no methods: it arrives from data(), compares with < <= > >=, and subtracts with - into milliseconds.
t and link
ttranslates a key:{ t('greeting', { name: user.name }) },{ t('cart.count', { count: items.length }) }. It's one of the standard functions, and it has strings to look up once translations are configured; see Translations.linkbuilds an href from a path that's correct for the router mode:href={ link('/posts/' + post.slug) }renders/posts/hellowith path routing and#/posts/hellowith hash routing, from the same template. See Routing.
What JavaScript already says
A function exists only where no method, operator, or Math global already says the thing. Uppercase with .toUpperCase(), lowercase with .toLowerCase(), trim with .trim(), replace with .replaceAll(a, b), join a list with .join(', '), and reach for Math.abs, Math.ceil, and Math.floor. Count with .length, do arithmetic with the operators, and fall back with ??.
There are no list functions. Array methods cover display shaping: {#for t in todos.filter(t => !t.done)}, { items.at(-1).title }, { tags.join(', ') }. Sorting by a rule, deduplicating, combining models, and anything a second view would repeat belong in data(). A call to a name outside the library, such as upcase or sort, passes the value through unchanged, and development logs what to write instead.
Rendering HTML: raw and newline_to_br
Every other interpolation renders a text node, so a value can never become markup by accident. Two functions render real HTML:
<article>{ raw(post.bodyHtml) }</article>
<p>{ newline_to_br(comment.text) }</p>
<div>{ raw(truncate(post.bodyHtml, 200)) }</div> <!-- the call inside raw runs on text -->rawalways sanitizes. The value passes through an allowlist sanitizer that runs identically in the browser and in prerendered pages. Document markup, links, and images survive, along withclass,id,title,lang, anddir.<script>,<style>,<iframe>,<svg>, and similar tags are dropped, forms and unknown tags are unwrapped to their text, everyon*handler andstyleattribute is removed, and a URL survives only when it's relative orhttp(s)(links also keepmailto:andtel:). A link may keeptarget="_blank", and a link that does always getsrel="noopener noreferrer".newline_to_brescapes the value and turns each line break into a real<br>, and nothing else.- Either one must be the outermost call of a text interpolation, with one argument. Calls inside it run on text. After it the value is markup, so
{ raw(x).trim() },{ escape(raw(x)) },title={ raw(x) }, a prop, a second argument, or use inside<script>,<style>,<textarea>, or<title>is a compile error.
Because class and id survive, sanitized content can pick up your CSS and can shadow an undefined global by id. For untrusted user HTML that's a UI-overlay risk to weigh, not code execution. The compiler lowers both functions itself, so an app function registered as raw is never called from a template, and no app function can inject markup. The rendering code ships only in apps that use one of them.
App functions
Register your own in the formatters map of the PuzzleApp config, then call them by bare name, like the built-ins:
// app.js
const app = new PuzzleApp({
target: '#app',
routes,
formatters: {
byline: (name) => (name ? `By ${name}` : 'By an unknown author'),
},
});<span>{ byline(author.name) }</span>- Functions are display-only. Data logic belongs in
data(), not the template. - A function must be pure. Loop rows are cached between renders and don't re-run their functions unless their inputs change, so a function that reads the clock or other ambient state would freeze its output.
- Don't shadow a standard name. An app function registered under a standard name wins, with a development warning, and changes what that name means across the app.
- A misspelled function doesn't crash. An unregistered name renders the value unchanged and logs one
console.errornaming it, with a did-you-mean suggestion. If a function seems to do nothing, check the console. - Static builds read functions from a file. For
output: 'static', export your functions fromapp/formatters.jsso each page's module can load them; see Static Builds.
Conditionals
{#if expr} renders its block when the expression is truthy. {:else} is optional, and any number of {:else if} clauses can sit between:
{#if user.isLoggedIn}
<p>Welcome back, { user.name }!</p>
{:else if user.isPending}
<p>Your account is almost ready. Check your inbox.</p>
{:else}
<p>Please sign in to continue.</p>
{/if}It's spelled else if (JavaScript), and {:else} must be last. A condition is one template expression, methods and function calls included: {#if items.length}, {#if post.title.startsWith('Draft')}. An empty list is truthy, so test .length when you mean "has items".
{#unless}
The mirror of {#if}: it renders when the expression is falsy, with an optional {:else}:
{#unless todos.length}
<p class="empty">No todos yet. Add one above.</p>
{:else}
<p>{ todos.length } to go</p>
{/unless}Use it for guards where {#if !(…)} reads awkwardly. {:else if} isn't allowed inside {#unless}; write an {#if} ladder instead.
{#case} / {:when}
Selects the first {:when} clause whose value matches by strict ===. List several values in one clause (a comma means OR) and add a trailing {:else} for the default. There's no fallthrough, and the first match wins:
{#case status}
{:when 'active', 'trial'}
<span class="badge badge-green">Live</span>
{:when 'suspended'}
<span class="badge badge-red">Suspended</span>
{:else}
<span class="badge">Unknown</span>
{/case}Loops
Iterate a list from the model, binding each element to the loop variable:
{#for todo in filteredTodos}
<div class="row">
<span>{ todo.text }</span>
<button @click={ deleteTodo(todo) }>×</button>
</div>
{/for}The loop variable is in scope everywhere inside the block: interpolations, attributes, and event bindings alike. A trailing , name binds the 0-based index:
{#for todo in filteredTodos, i}
<li>
<span>{ i + 1 }. { todo.text }</span>
<button @click={ moveUp(i) }>↑</button>
</li>
{/for}The range form repeats a block a fixed number of times, handy for placeholders. Its counter also goes after the range, so {#for i in 1...5} is a compile error that points you at {#for 1...5, i}:
{#for 1...5}
<div class="h-4 w-full bg-gray-200 rounded"></div>
{/for}
{#for 1...3, n}
<li class="step">Step { n }</li>
{/for}What a loop accepts:
- A list iterates. A missing collection (
nullorundefined) loops zero times silently. Anything else that isn't a list (a string, an object, a number) loops zero times with a development warning, so a loop never walks a string's characters. - Range bounds are whole numbers. A fractional bound is truncated with a development warning; a numeric string such as a route param's
'5'is fine. A missing bound, or an end below its start, runs zero times. - The collection is any expression, an array method included:
{#for t in todos.filter(t => !t.done)}. For a list the view needs more than once, or one that takes real logic, build it indata()and loop over that field.
Keys and row caching
Rows are keyed automatically. A store record keys by its model's primary key, and any other value keys by its .id. To key by something else, put an explicit key={ … } on the loop body's root element; keys must be stable and unique across the list. A row whose key comes out null logs a warning and falls back to positional diffing.
Keyed rows are also cached between renders: a row whose item and inputs haven't changed returns its previous output, and the patcher skips it. Two contracts follow from that. Update records through update() or a store path, never todo.title = 'x', which nothing observes. And keep functions pure. Plain objects and arrays are never cached, so rows built from them rebuild on every render.
Add a bare flip attribute to a keyed row's root and retained rows slide to their new positions when the list reorders. See Animations.
Attributes
Interpolation and inline {#if} inside attribute values
Both { expression } and inline {#if} blocks work inside a quoted attribute. This is the idiomatic way to apply conditional classes, a static base plus a conditional tail:
<span class="flex-1 text-gray-900 {#if todo.completed}line-through text-gray-500{/if}">
{ todo.text }
</span>
<button class="tab {#if currentFilter === 'all'}tab--active{:else}tab--idle{/if}" @click={ setFilter('all') }>
All
</button>Plain interpolation works too: title="Delete { todo.text }". The inline form is a flat {#if}…{:else}…{/if}; {:else if} isn't available inside an attribute.
Dynamic (bound) attributes
Use braces as the entire attribute value to bind it to an expression:
<button disabled={ !canAdd }>Add Todo</button> <!-- canAdd: a data() field -->
<a class={ [isActive && 'active', 'nav-link'] } href="/inbox">Inbox</a>
<img src={ user.avatarUrl } alt={ user.name } />A brace-only attribute keeps DOM attribute semantics rather than printing text:
false,null, andundefinedomit the attribute;truewrites it with an empty value.- A list is a space-separated token list.
falseand items that print nothing are dropped, soclass={ [active && 'on', 'btn'] }writesclass="btn"whenactiveis false. - An object omits the attribute, with a development warning.
- Everything else prints by the value rule above.
A quoted attribute with an interpolation (data-x="{ x }") is text: a null value writes the attribute empty instead of omitting it.
Two-way form binding
On a plain <input>, <textarea>, or <select>, a value= or checked= whose expression is a bare data key or a one-member path binds both ways, with no handler to write:
<input type="search" value={ query } /> <!-- local state -->
<input type="checkbox" checked={ todo.completed } /> <!-- a record field -->A bare key writes local state and re-runs data(), so derived values stay live as you type. A member path on a store record writes through the record's validated update(). Anything else, such as value={ draft ?? '' } or a function call, stays a one-way display binding. The full rules, including which event commits and how to opt out, are in Events & Binding.
Whitespace
Template text renders the way the same markup renders in a browser, without your source indentation leaking into the page. A run of spaces, tabs, and newlines collapses to one space, and three rules decide where that space survives:
- Between text and an element, it becomes one space, in either order. Prose that wraps around inline elements reads correctly.
- Between two elements, a line break is dropped. Stacked buttons, badges, and conditional blocks get no gap. The same goes for a parent's first and last child indentation.
<pre>and<textarea>bodies are preserved exactly, except the one newline directly after the start tag, which HTML drops too.
<p> Read the <a href="/guide">guide</a>, then start building. </p> <!-- renders: Read the guide, then start building. --> <div class="actions"> <button>Save</button> <button>Cancel</button> </div> <!-- no text node between the two buttons -->
Nothing is invented where the source has no whitespace: <b>x</b>{ y } stays adjacent. When two things must touch, write them on one line with nothing between them. A flex or grid item ignores leading and trailing spaces, so an icon on one line and its label on the next inside a flex button looks the same either way. A <pre> indented along with the template shows that indentation, so dedent its body or bind it ({ code }).
Slots
Composition markers are capitalized and written either self-closing or paired with a body. A layout marks the router outlet with <Slot/>; a reusable component marks where its call site's content lands with <Children/>:
<!-- layouts/Default.pzl: the router outlet --> <puzzle-view class="shell"> <main><Slot/></main> </puzzle-view> <!-- components/Button.pzl: the call site's content --> <puzzle-view> <button class="btn"><Children/></button> </puzzle-view>
A route's view renders at its layout's <Slot/>, and children written at a component's call site render at that component's <Children/>. They compile to the same marker; the split is a convention that keeps a template's intent readable. Writing either marker in lowercase (<slot> or <children>) is a compile error that names the capitalized form.
Named slots
Multi-region components declare named slots with <Slot name="…"/> alongside the default <Children/>:
<!-- Card.pzl -->
<puzzle-view>
<div class="card">
<header><Slot name="header"/></header>
<div class="body"><Children/></div>
<footer><Slot name="footer"/></footer>
</div>
</puzzle-view>At the call site, a static slot="name" attribute on a direct child routes that child into the matching region, and the attribute is stripped from the output. Direct children without one form the default content:
<Card>
<h2 slot="header">{ post.title }</h2>
<p>{ post.excerpt }</p> <!-- default slot -->
<Button slot="footer">Read</Button>
</Card>The name must be static and non-empty (name="default" and name="children" are reserved; both steer to <Children/>). Slot targeting applies only to a direct child of the component tag; anywhere deeper, slot is the ordinary HTML attribute. A routed view or layout only ever fills the default slot.
Fallback content
Write a marker in its paired form and the body is fallback content: it renders only while nothing fills that position. This is how a component ships its own default chrome:
<!-- components/Button.pzl: the label a caller usually doesn't override -->
<puzzle-view>
<button class="btn"><Children>Save</Children></button>
</puzzle-view>
<!-- components/Card.pzl: a named slot with stock footer chrome -->
<puzzle-view>
<div class="card">
<div class="body"><Children/></div>
<footer><Slot name="footer"><button class="btn">OK</button></Slot></footer>
</div>
</puzzle-view>
<!-- layouts/Files.pzl: the router outlet's fallback -->
<puzzle-view class="shell">
<main><Slot>No file selected</Slot></main>
</puzzle-view>Whatever fills the position replaces the fallback entirely. Nothing merges:
<Button/> <!-- Save, the fallback -->
<Button>Delete</Button> <!-- Delete; the fallback is gone -->
<Card>
<p>{ post.excerpt }</p> <!-- footer: the stock OK button -->
</Card>
<Card>
<p>{ post.excerpt }</p>
<Button slot="footer">Publish</Button>
</Card> <!-- footer: Publish, in place of OK -->A position counts as filled only when the content supplied for it renders at least one node that isn't whitespace. A call-site {#if} that is false, or a {#for} over an empty list, leaves the position unfilled, so the fallback shows. That gives you the empty state for free:
<!-- List.pzl -->
<puzzle-view>
<ul class="list"><Children><li class="empty">Nothing here yet</li></Children></ul>
</puzzle-view>
<!-- call site: an empty list shows the fallback -->
<List>
{#for item in items}
<li>{ item.name }</li>
{/for}
</List>A few more rules:
- A self-closing marker has no fallback and renders nothing when unfilled; an empty paired body means the same. There's no way to ask whether a call site filled a slot, because the fallback body is the mechanism.
- A fallback body is ordinary template content: interpolations, function calls, blocks, components, event bindings, refs, and
{#svg}all work inside it. The one restriction is that a marker can't sit inside another marker's fallback body. - One default marker per render path. Markers in mutually exclusive
{#if}/{:else}or{#case}branches are separate paths, so{#if compact}<div><Children/></div>{:else}<section><Children/></section>{/if}compiles. Two markers that can render together are a compile error. The same holds per named slot. - Keep a fallback to one root element when siblings follow the marker. Unkeyed siblings are patched by position, so a fallback whose node count differs from the content it swaps with remounts the siblings after it.
The router outlet behaves the same way: a layout's <Slot>fallback</Slot> shows its body when no child route occupies the outlet.
Snippets
A slot renders a passed-in template once. A snippet is a template the component can stamp repeatedly, with fresh data each time: the caller declares a <Snippet> with parameters, and the component hands values to its own marker:
<!-- caller: declare what a row looks like -->
<UserList users={ users }>
<Snippet fits="row" user>
<img src={ user.avatar } alt="" /> <b>{ user.name }</b>
</Snippet>
</UserList>
<!-- UserList.pzl: stamp it once per user, with a fallback -->
<puzzle-view>
<ul>
{#for user in users}
<li><Slot name="row" user={ user }>{ user.name }</Slot></li>
{/for}
</ul>
</puzzle-view>fits="x"routes the snippet to<Slot name="x">; without it, the snippet fills the default<Children>. Every other attribute on<Snippet>is bare and declares a parameter.- Binding is by name. On the component side, every valued attribute on
<Children>or<Slot name>(other thanname) becomes an argument, and each snippet parameter picks up the argument with the same name. Declaring a subset is fine. - A marker inside a
{#for}stamps once per item, which is the point. A stamp that renders nothing shows the marker's fallback for that stamp. - A
<Snippet>is paired-only and must be a direct child of a component tag. Its body is a leaf: no<Children>,<Slot>, nested<Snippet>, orrefinside it. To nest, move the inner invocation into its own component. - Wrappers forward snippets. A bare
<Children/>inside a nested component invocation hands the caller's snippets through along with the default content.
Portals
<Portal>…</Portal> mounts its children into a framework-created outlet beside the app root, while they stay part of the owning component's tree. Use it for overlays and full-screen panels that must escape an ancestor's overflow or stacking context:
<puzzle-view>
<div style="display: contents">
<button @click={ toggle }>Filters</button>
{#if open}
<Portal>
<div class="drawer" @pointerdown:outside={ close }>…</div>
</Portal>
{/if}
</div>
</puzzle-view><Portal>is paired-only and takes no attributes.@event:outsidetreats portaled content as inside its owner, so a click inside the panel doesn't count as outside.- A portal can't be a component's template root; wrap it, for example in
<div style="display: contents">. A view whose template is only a portal is fine. - Portals render nothing in prerendered HTML. Their content appears once the page's JavaScript mounts.
- For a focus-trapped modal, prefer a native
<dialog>opened withshowModal()through a ref.
DOM islands
A bare island attribute on a plain element hands its children to the browser after mount. The template children render once, as seed content; after that the renderer never reconciles them, so an external mutation (a contenteditable edit, a chart library's DOM) survives every re-render. The element's own attributes and listeners keep patching normally:
<!-- Always-editable block: the framework seeds it, the browser owns it -->
<div contenteditable="true" island @input={ syncText(event) }>{ block.text }</div>
<!-- Third-party mount: seeded empty, filled by a library in mounted() -->
<div class="h-64" island></div>Data flows out of an island (events to the store), never back in. To reset one programmatically, change its key to replace and re-seed the node. island must be static and can't go on a component tag or the <puzzle-view> root, and no component or composition marker may sit inside an island.
Inline SVG
{#svg 'path'} inlines an SVG file from app/assets/ at compile time, which makes it the ergonomic choice for a shared icon set. It's a self-contained tag with no closer:
<button @click={ toggleCart }>
<span class="inline-block size-5">{#svg 'icons/cart.svg'}</span>
</button>The path is exactly one quoted static string resolved from app/assets/. The file's contents are dropped in verbatim and never template-parsed, so there's no { expr } or handler inside it. Style it from the parent (currentColor picks up text color; size it with a wrapper). For a reactive or animated SVG, paste the markup directly into the template.
Literal braces: {#raw}
A {#raw}…{/raw} block turns the brace grammar off for its body while HTML keeps parsing. Use it for JSON, code samples, and anything else that needs literal braces in template source:
<script type="application/json" data-options>
{#raw}{ "loop": true, "slidesPerView": 3 }{/raw}
</script>
<pre>{#raw}const shape = { a: 1, b: [2, 3] };{/raw}</pre>
<input name="zip" pattern="[0-9]\{5\}" />Inside the block, interpolations, block tags, and brace-valued attributes are all literal text, while <b> is still a real element. The body is static source that no runtime value can reach, so it isn't HTML injection. Raw blocks don't nest, can't appear inside an attribute value, and a literal {/raw} can't appear in the body.
For a single literal brace anywhere, attribute values included, escape it as \{ or \}. The form pattern idiom needs it: pattern="[0-9]\{5\}", since an unescaped {5} would be an interpolation. The raw function is unrelated: it renders a runtime value as sanitized HTML and can't make source braces literal.
Element refs
A static ref="name" on a plain element hands the view a live reference to that DOM node as this.refs.name, the declarative replacement for querySelector:
<puzzle-view class="search">
<input ref="search" type="text" value={ query } />
</puzzle-view>mounted() {
this.refs.search.focus(); // populated before mounted()
}
events = {
jumpToSearch: () => this.refs.search?.focus(), // guard elsewhere with ?.
};The framework keeps the reference honest: it re-points if a keyed replacement swaps the element, and becomes null while the element is unmounted. ref must be a static string, and it isn't allowed on component tags, inside a {#for}, or inside <puzzle-skeleton>. For a component handle, use the @ready callback prop (see Events).
Cheat sheet
| Construct | Syntax | Example |
|---|---|---|
| Interpolation | { expr } | { todo.text } |
| Function | { fn(value, args) } | { datetime(createdAt, 'short') } |
| Nested calls | { fn2(fn(value)) } | { truncate(capitalize(title), 40) } |
| Method | { value.method(args) } | { name.toUpperCase() } |
| Sanitized HTML | { raw(html) } | { raw(post.bodyHtml) } |
| Count | { list.length } | { todos.length } |
| Math, then format | { fn(a * b) } | { currency(price * qty) } |
| Fallback | { a ?? b } | { subtitle ?? 'Untitled' } |
| Template literal | { `text ${expr}` } | { `${first} ${last}` } |
| Arrow argument | list.method(x => expr) | {#for t in todos.filter(t => !t.done)} |
| Functions: numbers | roundcurrencypercentagenumber_with_delimitercompact_number | { compact_number(followers) } |
| Functions: text | pluralizecapitalizetruncatestrip_htmlstrip_newlines | { pluralize(n, 'comment') } |
| Functions: markup | escaperawnewline_to_br | { newline_to_br(note) } |
| Function: values | json | { json(settings) } |
| Functions: dates | datetimedatetimein_timezone | { datetime(at, 'short') } |
| Function: translation | t | { t('cart.title') } |
| Functions: PuzzleKit-only | linktimeago | { timeago(at) } |
| Conditional | {#if} … {:else if} … {:else} … {/if} | {#if todos.length > 0} … {/if} |
| Inverted | {#unless expr} … {/unless} | {#unless todos.length} … {/unless} |
| Multi-branch | {#case expr}{:when v} … {:else} … {/case} | {#case status}{:when 'active'} … {/case} |
| Loop (items) | {#for item in items, i} … {/for} | {#for todo in todos, i} … {/for} |
| Loop (range) | {#for 1...n, x} … {/for} | {#for 1...5} … {/for} |
| Row key | key={ expr } on the body root | <li key={ row.slug }> |
| Attr interpolation | attr="text { expr }" | title="Delete { todo.text }" |
| Conditional class | class="base {#if e}extra{/if}" | class="tab {#if active}on{/if}" |
| Dynamic attribute | attr={ expr } | disabled={ !canAdd } |
| Two-way input | value={ key } or value={ record.field } | <input value={ query } /> |
| Event (bare) | @event={ handler } | @click={ clearCompleted } |
| Event (call) | @event={ handler(args) } | @submit={ addTodo(event) } |
| Event + modifiers | @event:mod={ handler } | @keydown:enter={ addTodo(event) } |
| Component + props | <Name prop={ expr } /> | <UserProfile userId={ id } /> |
| Component family | <Name.Member> | <Frame.Wrapper> |
| Default marker | <Children/> or <Children>fallback</Children> | <button><Children>Save</Children></button> |
| Router outlet | <Slot/> or <Slot>fallback</Slot> | <main><Slot/></main> |
| Named slot (child) | <Slot name="…"/> or <Slot name="…">fallback</Slot> | <Slot name="header"/> |
| Named slot (call) | slot="…" on a direct child | <h2 slot="header">{ title }</h2> |
| Snippet (call) | <Snippet fits="…" param>…</Snippet> | <Snippet fits="row" user>{ user.name }</Snippet> |
| Snippet (component) | <Slot name="…" param={ expr }/> | <Slot name="row" user={ user }/> |
| Portal | <Portal>…</Portal> | <Portal><div class="panel">…</div></Portal> |
| DOM island | <el island>seed</el> | <div contenteditable island>{ text }</div> |
| Inline SVG | {#svg 'path'} | {#svg 'icons/cart.svg'} |
| Literal braces | {#raw} … {/raw} or \{ \} | pattern="[0-9]\{5\}" |
| Element ref | ref="name" → this.refs.name | <input ref="search" /> |
| Comment | {## text } / {#comment} … {/comment} | {## TODO } |
Next
- Events & Binding: the handler model and form binding in full.
- Components: the
.pzlfile and its lifecycle. - Translations: the
tfunction and locale files.
Comments
Template comments are erased at compile time, leaving no DOM node and nothing in the bundle:
{## inline note, discarded up to the closing brace } {#comment} A block comment. The body is discarded raw, so it can hold anything: { interpolations }, {#if}half-written{/if} blocks, none of it is parsed. {/comment}Use the block form to comment out broken or in-progress markup: its body is never lexed, so it simply disappears. HTML comments (
<!-- -->) are also stripped and never reach the DOM.