Template Syntax and Styles
Templates
Example: Template Primitives shows its code and downloads as a project.
<head><title>${data.post.title}</title></head>
<h1 class="text-3xl font-bold">${data.post.title}</h1>
{#if data.posts.is_empty()}
<p>No posts.</p>
{:else if data.posts.len() == 1}
<p>One post.</p>
{:else}
{#each data.posts as post, i}
<a href="/blog/${post.slug}" class=${post.class()}>${i}: ${post.title}</a>
{:else}
<p>Empty.</p>
{/each}
{/if}
{#match data.status}
{:case Status::Draft} <span>draft</span>
{:case Status::Live(date)} <time>${date}</time>
{/match}
{@const total = data.posts.len()}
{@html data.trusted_svg}
| Syntax | Compiles to |
|---|---|
${expr} | Escaped Display; None writes nothing |
attr=${expr} | attr="…", quotes added, value escaped |
disabled=${cond} | disabled if cond, else nothing |
<a href="/blog" active> | aria-current=${wisp::current(..)} |
{@html expr} | Unescaped Display |
{@const x = expr} | let x = expr; |
{#if c}…{:else if c}…{:else}…{/if} | if/else; a bare place like {#if user.avatar} tests Some, non-empty or true |
{#each e as pat[, i] [if cond]}…{:else}…{/each} | for; if cond keeps matching items |
{#match e}{:case pat}…{/match} | match |
{#await f}…{:then v}…{:catch e}…{/await} | The page streams v or e later (streaming) |
{@render children()} or <slot /> | Layout or component slot |
<>…</> | A fragment: its children, no element |
{#snippet row(item, i)}…{/snippet}, {@render row(x, 0)} | Markup to render later, here or in a component |
<head>…</head> or <wisp:head>…</wisp:head> | Appended to the document head |
<title>…</title> at top level | Same as in <head>; the innermost wins |
<title description="…" image="/og.png">T</title> | Title plus description, og:* and twitter:card meta |
{@flash} | The cx.flash(..) message, once |
${cx.path()} | cx is the request (&Cx) |
${x | upper} | A filter, chainable; see Filters |
<a ${...attrs}> | Attribute pairs (wisp::rt::spread); see Spreads and Styles |
style:color=${c} | color:…; in the tag's style |
<a ${href}>, <Card ${title} /> | Shorthand for href=${href} |
{#if loop.last} | loop.first, loop.last, loop.index, loop.odd, loop.even (a wisp::Loop) |
{~#if x~}, ${~ name} | ~ trims the blanks on that side |
{@id f} | let f: an id unique in the page |
{@debug user, n} | Prints values in a debug build (wisp dev) only |
<script type="application/ld+json">{@json page}</script> | The value as JSON, the whole body of a script the browser does not run (JSON-LD, a data block); see JSON in a script |
<wisp:component this=${kind} …/> | The component kind names; see Dynamic Components |
<!--! MIT License --> | Kept as a comment; others are stripped |
<wisp:window on:keydown="…" /> | Handlers on window, <wisp:document>, <wisp:body> (Browser code) |
<div {@attach f}> | Browser code: f(el) runs in an effect, its returned cleanup at the end (Attachments) |
- Expressions are Rust, so type errors are real. A bare
{is text, so CSS and JS need no escaping inside<script>and<style>. Write a literal${as${"${"}. - A format spec in a hole (
${page:?}) is a build error: write${format!("{:?}", page)}. An{#each}item namedcxis an error too. - The build splits a hole that is one
format!("..")call. The build escapes the fixed text once. A{name}capture writes as${name}does. The hole makes noString. - A hole is HTML-escaped, not percent-encoded. For a query use
wisp::query_string:href="/prefs${wisp::query_string(&[("lang", "fr"), ("next", cx.url())])}".
Filters
<p>${post.title | upper} · ${post.body | truncate(120)} · ${price | money("EUR")}</p>
<span>${user.nick | or("anonymous")}</span> <time>${post.date | date}</time>
<p>${post.tags | join(", ")}</p>
| Filter | Writes |
|---|---|
upper, lower, capitalize | Case changed |
trim | Blanks removed at both ends |
truncate(n) | At most n characters, then … |
number, money("EUR") | wisp::format_number, wisp::format_money |
date, date_long | wisp::format_date, wisp::format_date_long |
json | JSON, for a data-* attribute |
or("text") | The text for None |
join(", ") | The items of a Vec, slice, array, VecDeque or BTreeSet |
- Filters use the app's default locale; for the visitor's call
${wisp::format_money(p, "EUR", cx.locale())}. - Closures and
||stay Rust; write bitwise or as${(a | b)}. Filters work in text, attribute values and{@html x | f}, not in spreads, blocks, component props or browser holes.
Mistakes the Build Explains
An error names the file and line and suggests the nearest block, tag or filter: did you mean {#each}?. Foreign syntax gets the Wisp spelling: {{ x }} is ${x}, {% if %}, {% for %}, {% set %}, {% include %}, v-if, v-for, v-html and className get {#if}, {#each}, {@const}, a component tag, {@html} and class.
Blocks nest at most 128 deep. <template each> and <template if> elements also nest at most 128 deep. A deeper file fails with blocks nested more than 128 deep or <template> elements nested more than 128 deep (W0104).
Spreads and Styles
<a ${...link_attrs} class="btn" style:color=${accent} style:--gap=${gap}>Go</a>
${...attrs}takes pairs of(name, value): a slice, array,Vec,BTreeMap,HashMapor anOptionof one. AHashMapwrites its pairs in the order of its keys. Put attributes that must win before the spread. A spread and an attribute hole (title=${t}) keep a blank between the text before and after them. So a name never joins an unquoted value. An=right after a spread is an error.style:name=${value}joins the tag'sstyleattribute, asclass:name=${cond}joinsclass. Wisp writes no value that could leave its declaration or run script.style:name="js"is the browser's. A hole inside astyleattribute (style="color:${c}") takes the same filter. A hole in the name of a declaration (style="-moz-${x}:v",style="a:b;${c}") is a build error:a `${}` in a `style` attribute must come after `name:`. A property name must be text in the file. Write style="color:${value}" or style=${declarations}. A wholestyle=${s}, or astylepair handed to${...attrs}, keeps only its plainname:valuedeclarations. A${in a<style>element is a build error: its CSS does not change. Usestyle:name=${v}or aclass:.
Loops, Ids and Debugging
<ul>
{#each items as item}
<li class:first=${loop.first}>${item}{#if !loop.last},{/if}</li>
{/each}
</ul>
<!-- src/components/Field.wisp -->
{@props label: &str}
{@id f}
<label for=${f}>${label}</label> <input id=${f} name=${label | lower}>
{@debug label}
loopis awisp::Loopwithindex(from 0),first,last,oddandeven. Outside{#each}it is a build error.{@id f}is aStringunique in the page and the same at every render. Browser code has$props.id().
Dynamic Components
{#each blocks as b}
<wisp:component this=${b.kind} text=${b.text} />
{/each}
<wisp:component this=${kind} of="Hero Quote" text=${t} />
this is a &str or String naming a component. The build writes a match over the components of="…" lists, else every component that takes the props given. An unknown name draws nothing. Server-drawn only; in browser code use {:#if}.
Whitespace and Comments
<b>{~#if x~} yes {~/if~}</b> is <b>yes</b>. Comments never ship; write <!--! … --> for one that must.
Coming from Svelte
Svelte's {x} is ${x}; class:x={c} is class:x=${c}; on:click|preventDefault is on:click.prevent. <svelte:window>, <svelte:document>, <svelte:body>, <svelte:head>, <svelte:element> and <svelte:component this> are <wisp:window>, <wisp:document>, <wisp:body>, <head>, <wisp:element> and <wisp:component this=${name}>. <svelte:fragment> is <>…</>, and <svelte:boundary> is {:#try}…{:catch e}…{:/try} in the browser, and its pending snippet is {:await} before {:catch}. <svelte:options> and <svelte:self> are not taken.
Escaping and Refused Places
Escaping covers & < > " '. The parser tracks where each hole lands. It refuses:
on*attributes,srcdocand tag names (<${x}>)- a bare
<in text - a URL attribute starting
javascript:orvbscript: - a
data:URL in an<iframe>,<frame>,<object>,<embed>,<a>,<area>,<form>,<button>or<base> - an unquoted value mixing text and a hole (
href=/u/${id}: quote it) - an SVG
<animate>'sto,from,values,by - a
<meta>'shttp-equivandcontent - a
<script>'s or<base>'s URL unless a written origin comes first (below) - a quote that does not follow
=(the browser keeps it as text in an unquoted value or a name: writename="…") - an
=that does not follow an attribute name - a tag name that a byte other than a blank,
/or>ends - a block or a hole right after an unquoted value (quote the value or write a blank before it)
//comments inside a hole
An unquoted value can hold = and / (href=/a?b=c), as in HTML, but /> ends it.
When an expression decides a URL's scheme (href=${link}), wisp::rt::guard_url turns a script-running value into about:invalid#blocked. On a tag that loads its URL as a document (<iframe>, <frame>, <object>, <embed>), it also blocks a data: or blob: value. A data:text/html document there runs script. A media tag such as <img src=${u}> keeps data: pictures. <a href=${u} download> keeps a data:/blob: download (a browser blocks top-level data: navigation anyway). Wisp blocks href="/${p}" when p starts with / or \.
A <script src>, an SVG script's href and a <base href> can have a hole after a written https://host/: <script src="https://cdn.example.com/v1/${file}.js"></script>. The file sets the origin. Each hole is one percent-encoded piece of the path or query: /, ?, #, @ and : become %2F, %3F, %23, %40, %3A. So a hole cannot choose the host, the scheme or a user. A value of exactly . or .. would be a path step that the URL parser removes. So Wisp writes its dots as %252E. A hole in these places stays an error:
- first in the value (
src="${u}") - after only part of the host (
https://host${x}) - after
http:,//hostor/path - after userinfo (
https://a@evil/) - in an unquoted value, or after a block
- in a
<meta>'shttp-equivorcontent, or insrcdoc
JSON in a script
{@json expr} as the whole body of a <script> writes expr as JSON. It takes any wisp::Json value: a #[model], #[derive(Json)], numbers, text, lists, options. Wisp escapes <, >, &, U+2028 and U+2029 in strings (\u003c/script\u003e). So no value can end the script or open a comment. A last pass over the whole text does the same for a Json impl written by hand. It works in <head> too.
<head>
<script type="application/ld+json">{@json ld}</script>
</head>
<script type="application/json" id="boot">{@json boot}</script>
<script>const boot = JSON.parse(document.getElementById("boot").textContent)</script>
Only a script the browser does not run takes it: a type that is not JavaScript, a module or an import map (application/ld+json, application/json, speculationrules), and no src. A script that runs is allowed by the hash of its text in the page's Content-Security-Policy, which a body that changes per request cannot have, and a nonce on every page would cost the cache. So a running script gets data from a data block, with no unsafe-inline and no nonce, and {@json} in one is a build error that says so. Anything else in the body next to it is an error.
Components
A .wisp file in src/components (any depth) is a component named by its file: Card.wisp is <Card>. It declares its props at the top:
<!-- src/components/Card.wisp -->
{@props title: &str, count: usize = 0, featured: bool = false}
<section class="card">
<h2>${title}{#if featured} ★{/if}</h2>
<p>${count} items</p>
{@render children()}
</section>
<Card title=${post.title} count=${post.tags.len()} featured>
<Badge label="new" />
</Card>
<Card title="Drafts" />
- Props are Rust types; bare
nameistrue. --color="red"or--gap=${gap}on the tag sets a CSS custom property the component reads withvar(--color, black). Wisp drops a value that could end the declaration or load a file (such as;,{,},url(or a control character).{@render children()}shows what the tag wraps. Children see the using page'sdataand{@const}s.- A prop cannot be named
self,Self,crate,super,_orchildren. The browser can draw components too: Browser code.
Snippets
{#snippet row(post, i)}
<td>${i}</td><td>${post.title}</td>
{/snippet}
<table>{#each data.posts as post, i}<tr>{@render row(post, i)}</tr>{/each}</table>
<Table rows=${data.posts} ${row} />
<Table rows=${data.posts}>
{#snippet row(post, i)}<td>${post.title}</td>{/snippet}
</Table>
<!-- src/components/Table.wisp -->
{@props rows: &[Post], row: Snippet<&Post, usize>}
<table>{#each rows as r, i}<tr>{@render row(r, i)}</tr>{/each}</table>
- Parameters are Rust
letpatterns. Define a snippet before its{@render}; it cannot render itself. - A component takes one as a prop of type
Snippet<A, B>(Snippetfor none):${row},row=${row}or a{#snippet}among the children.
Scoped Styles
<h1>Hi</h1>
<style>
h1, .lead {
color: rebeccapurple
}
:global(body) {
margin: 0
}
</style>
- A
<style>without attributes is that file's. Its elements getclass="w-xxxxxx"(a hash of the path) and each selector gets.w-xxxxxxon its last compound:.card p:hoverbecomes.card p.w-xxxxxx:hover. :global(x)isx, unscoped. A comma list,:global(.a, .b) p, becomes:is(.a, .b) p, so the list stays one selector. A<style>with any attribute (<style global>,media="print") is copied as written.@media,@supports,@container,@layerand nesting are scoped inside.@keyframes spinbecomesspin-w-xxxxxx, with its uses inanimationandanimation-name. Write-global-spinfor a shared name.@font-facestays global.@importis a build error: put it insrc/app.css.- Top level only. Elements your script makes get no class: use
:global(…). No class goes on<html>,<head>,<body>or<script>. - The CSS is appended to
/_app/app.css. Dev reads.wisp/scoped.css.
Is This Page Useful?