Pages and Templates
A page's Rust goes between two --- lines at the top of its .wisp. The markup follows.
The Block
- Items (
fn,struct,use,static,const,impl,#[action]) belong to the page's module. Statements run per request before the markup, in anasyncfunction returning aResult(.await,?,return redirect("/")).cxis&mut Cxthere and&Cxin markup. - Route params are locals:
slug: Stringfor[slug],id: u64for[id=int],Option<String>for[[lang]]. cx.route()is the matched pattern (/blog/[slug],""on a 404):class:on=${cx.route() == "/blog/[slug]"}. Browser code haspage.value.route.+page.rsis for Rust that outgrows the block (aloadreturningData, plus actions). A page has a block or a+page.rs, not both.mod server { … }in the block holds the route's endpoints (getpostputpatchdeletelist,before). Not with a+server.rsbeside it. Example.- A page and its endpoints can both take a GET (or
list), and a POST when the page has actions. The page answers a request from Wisp's client (x-wisp) or one whoseacceptnamestext/html(a browser navigation). The endpoint answers the other requests, and everyput,patchanddelete. HEAD follows GET. A form post to?/namefrom a browser goes to the action. Both answers sendvary: accept, x-wisp, andCACHEkeeps them apart. Every endpoint method of the route passes the page's guards (SIGNED_IN,MIDDLEWARE,RATE_LIMITorCORS): also aput,patchordelete, apostof a page with no action, and the member route/[id]. It passes the layouts' guards and its own guards too.CORSruns once, first: the endpoint's, else the page's. An endpoint that must stay public goes to another route. Anytext/htmlinacceptpicks the page: Wisp reads no q-values (SvelteKit does), sotext/html;q=0picks the page too. Amod serverand a+server.rstogether are still a build error. The build adds this test only to such routes. +layout.wispand+template.wisptake a block with no.awaitor?. Components and error pages take none.fn entries() -> Vec<…>in a page under[params]lists the pageswisp build --staticwrites (Deploying).
Parent data and imports
fn load(parent: &Parent) -> Data reads the Data of the nearest +layout with a load (its Data must be pub). The build rejects &Parent elsewhere.
A route file needs no use or pub. It has wisp::prelude, the pub items of the app's modules, HashMap HashSet BTreeMap BTreeSet VecDeque Arc Rc Cow Duration Instant SystemTime, and what [package.metadata.wisp] auto = ["chrono::{Utc, DateTime}"] lists. A name two modules make pub is a build error. wisp check --explain-imports shows where each name comes from. {@flash} and active work in pages and layouts, not components.
One File or Several
One +page.wisp holds models, Tables, #[action]s, helpers and the load, then markup (A Page Is One File shows its code). This is src/routes/todos/+page.wisp:
---
#[model]
struct Todo {
#[validate(len = 1..=100)]
text: String,
}
static TODOS: Table<Todo> = Table::saved(); // "todos"
#[action]
fn add(todo: Todo) {
TODOS.add(todo)?;
}
---
<title>Your todo list (${TODOS.len()})</title>
<meta name="description" content="Add todos with a form; each one is kept in a saved table.">
<h1>Todos</h1>
<form action="?/add" fields><button>Add</button></form>
{#each TODOS.all() as todo}
<p>${todo.text}</p>
{/each}
Items in a block are private to the page. Models and tables several pages use go in src/db.rs (or any src/NAME.rs), including the users table behind cx.user and login (Sessions). +server.rs is a route with no page; src/hooks.rs runs before once the route is found, for every app request and a 404, but not for /_wisp/*, /_app/*, static files, trailing-slash 308s, redirects or the sitemap/robots fallbacks.
Signatures and Inputs
load, actions and +server.rs endpoints may be fn or async fn, take cx or not, and return a plain value or a Result. Other parameters are inputs, read by name: route param, then POST/PUT/PATCH form, then query.
| Type | Behavior |
|---|---|
T (any FromStr) | Required. Missing: 400 naming the field (422 from a JSON body). Sent but not a T: 422 by field (400 from the query). A route param that does not parse: 404 |
Option<T> | None when missing or blank |
bool | Checkbox: sent, and not false, off, no, 0 or empty |
Vec<T> | Every value of a repeated field |
&str, Option<&str> | Borrowed from the request (read owned when the handler also takes cx) |
cx.form() reads anything else, files too. cx.input(name) finds one field.
Errors, Actions, Validation
?on astd::error::Erroris a 500.return error(404, "…")stops with that status,return redirect("/…")is a 303.Error::new(status, "…")andError::redirect(status, "/…")build them.Option::or_404()andor_status(409)(traitOrStatus) are shortcuts.Err(error(..))is a build error.- An action returns nothing, a
Result<()>or aResponsesent instead of the page. - Validation: return
invalid(field, problem). The page renders again as a 422 with each input showing what was typed and what is wrong (Actions). A param that does not parse (email: Email) gives the same 422.${cx.problem(field)}places a message;cx.fail(status, value)keeps a value the load takes withcx.take(). +server.rsmethods return aResponse, any other value as JSON (#[derive(Json)]), nothing as 204.body: Treads a JSON body asFromJson. Errors under/apiare JSON (APIs).
Limits and Caching
| Const | Effect |
|---|---|
const BODY_LIMIT: usize = 20 * wisp::MB; | Max body (default 1 MB, WISP_BODY_LIMIT), else 413 |
const CACHE: u32 = 60; | Keep GET answers, seconds |
const CACHE_PUBLIC: u32 = 60; | Also for cookie requests |
const CACHE_STALE: u32 = 600; | Serve stale, refresh behind |
const CACHE_TAGS: &[&str] = &["posts"]; or cx.cache_tag("post-7") | Name kept answers |
wisp::revalidate_tag("posts") drops a tag's answers on every worker and the wisp::cache_tagged answers with that tag, wisp::revalidate_path("/blog/x") one path, uncache a path and those below it. Each const is a u32 set once per route, not in a layout (BODY_LIMIT is a usize). The build adds each upload action's max_size to the body limit, so uploads need no BODY_LIMIT.
To share cache times across routes (as named cache profiles), set each pub const once in src/conf.rs (with mod conf; in main.rs). Then use it in each route. CACHE_STALE can use one the same way.
pub const HOURS: u32 = 3600; // src/conf.rs
pub const DAY: u32 = 86400; // src/conf.rs
const CACHE: u32 = crate::conf::HOURS;
const CACHE_STALE: u32 = crate::conf::DAY;
CACHE is per worker, keyed by Host, path and query. Only a 200 without a cookie or cache-control: private/no-store is kept, with an ETag. A write does not clear it; use uncache or revalidate_*. A new process starts empty. Requests with a cookie or authorization header skip it unless CACHE_PUBLIC. A kept CACHE_PUBLIC answer sends cache-control: public, s-maxage=<CACHE>, stale-while-revalidate=<CACHE_STALE> (no stale-while-revalidate when CACHE_STALE is 0), so a CDN can keep it. Your own cache-control wins. No such header when the app has a before or after hook, or when the page or its layouts have a guard (SIGNED_IN, MIDDLEWARE, RATE_LIMIT, CORS). The same holds when a +server.rs has a before function or a guard. Those run on each request and a CDN skips them. Set your own cache-control then. There is also no such header when the answer depends on accept: a page that shares its path with an endpoint, or a #[derive(Rest)] list. A CDN that skips vary can send one answer to the wrong client. A plain CACHE page sends none: a CDN that keys on the URL can send its copy to a signed-in visitor. Set your own cache-control on it if your CDN keys on the cookie too. A stale reply keeps s-maxage=<CACHE>, so a CDN can keep a page up to 2 × (CACHE + CACHE_STALE) after its render. A PPR page (a shell with holes) gets no such header: its holes are per request. In an app with locales, a page whose locale comes from the lang cookie or Accept-Language (no lang in its path, no domain, prefix not as-needed) gets no such header. A CDN hit does not reach the server: no before hook, rate limit, log, hook header or x-request-id. A CACHE_PUBLIC page behind a before gate (sign-in, paywall, geo) reaches everyone through a CDN. To keep the copy in the server and stop the CDN copy, set your own cache-control: no-cache (not private or no-store: then Wisp does not keep the page). revalidate_tag, stale_tag and uncache do not purge a CDN: it holds the old page until its s-maxage ends. A page that reads a header such as accept-language varies by it, so don't CACHE it. Dev keeps nothing. Limit: 8 MB per worker. A full store deletes the dead entries first, then the live entries nearest their end time (one eighth of the limit at a time). A flood of new URLs can push out pages that clients asked for. It costs renders, never memory.
Draft mode: cx.enter_draft() (from your own endpoint) sets the signed cookie wisp-draft; cx.exit_draft() ends it and cx.draft() reports it. Draft requests skip a CACHE_PUBLIC cache.
A page that reads nothing of the request needs no CACHE: with no load, statements or +page.js, and only literal holes, the build writes the response into the binary (Build).
Holes (Partial Prerendering)
On a page with CACHE, CACHE_PUBLIC or PRERENDER, an {#await} that does not name cx is waited for and kept. One that names cx is a hole: the page becomes a shell kept per worker (for good with PRERENDER), and each request runs the holes, which may read cookies or the user, and streams their answers in place of the pending markup. No script is needed.
---
const CACHE: u32 = 60;
---
<h1>Shop</h1>
{#await cart(cx.cookie_or("cart", String::new()))}<p>…</p>{:then c}<p>${c.len()} items</p>{/await}
cxin the shell (markup, statements,load, layouts) is a build error;cx.cache_tagis fine. Also refused: a hole naming alet, a hole inside{#if}or{#each},{@flash},<form once>,<form guard>andCACHE_STALE.- The shell is kept only from a GET that set no cookie, sent as
cache-control: private, no-store.uncache,revalidate_pathandrevalidate_tagdrop it. - In
wisp build --staticholes keep their pending markup.
Accessibility
wisp check, wisp dev and wisp build lint each template and warn ((a11y-img-alt)). Every lint has a code and a level: see Lint levels. <!-- wisp-ignore a11y-img-alt --> on the line before an element silences a lint. A value set by an expression counts as set.
Lints (wisp check --rules lists them all):
| Code | Finds |
|---|---|
a11y-img-alt | <img> without alt |
a11y-img-redundant-alt | alt that says image, picture or photo |
a11y-anchor-href | <a> without href, or href="#" |
a11y-link-name, a11y-button-name | a link or button with no text, aria-label or <img alt> |
a11y-input-label | a control with no label, id, aria-label, title or placeholder |
a11y-label-control | <label> that labels nothing |
a11y-heading-order | a heading that skips a level |
a11y-click-events | on:click on a non-interactive element without role and on:keydown |
a11y-mouse-events | on:mouseover without on:focus, on:mouseout without on:blur |
a11y-inline-handler | a literal onclick="..." or other on*="...", which the page's CSP blocks: write on:click |
a11y-autofocus, a11y-accesskey | the attribute |
a11y-tabindex | tabindex above 0 |
a11y-tabindex-static | tabindex="0" on an element with no role, no label and no handler |
a11y-interactive-focus | an interactive role and a click, but no tabindex |
a11y-aria-attr | an aria-* name that is not an ARIA attribute |
a11y-aria-role | a role that is not a WAI-ARIA 1.2 role |
a11y-role-redundant | a role that the element has (<button role="button">; <ul role="list"> is left) |
a11y-role-props | a role without the ARIA attributes it requires (role="checkbox" needs aria-checked) |
a11y-aria-hidden-focusable | aria-hidden="true" on an element that takes focus |
a11y-media-captions | <video> without <track kind="captions"> (a muted video is skipped) |
a11y-iframe-title | <iframe> without a title |
a11y-distracting | <marquee> or <blink> |
Lint levels
Set the level of a rule, or of a group (a11y, seo, css, js, onion), in Cargo.toml. A rule wins over its group.
[package.metadata.wisp.lint]
a11y = "error" # every a11y-* rule fails the build
a11y-img-alt = "warn" # except this one
js-console = "warn" # off by default
css = "off"
off drops the warning, warn prints it and error fails the build. strict = true fails on every warning. An unknown rule is an error that names the nearest code. Wisp reads the levels only under the exact header [package.metadata.wisp.lint]. A key that starts with lint under [package.metadata.wisp] (lint.a11y = "off", lint = {...}), a header that only looks like it ([ package.metadata.wisp.lint ]) and a row without = in the table are errors. wisp check --rules lists each rule with its level.
CSS and JavaScript lints
These read the <style> and <script> blocks of templates and the .css, .js, .mjs and .ts files in src/. They use the tokenizer of the build, not a new parser. // wisp-ignore js-var, /* wisp-ignore css-empty-rule */ or <!-- wisp-ignore js-var --> on the line before a finding (or on it) silences it.
| Code | Level | Finds |
|---|---|---|
css-empty-rule | warn | a rule with no declaration |
css-duplicate-property | warn | a property twice in one rule (a fallback with another value right after is fine) |
css-color-hex | warn | a hex color with a wrong length or a wrong digit |
css-at-rule | warn | an at-rule that CSS and Tailwind do not define |
css-important | off | !important |
js-debugger | warn | a debugger statement |
js-eqeq | warn | == or != (except against null) |
js-unused-import | warn | an import that nothing in the file uses (a template's markup counts) |
js-var | off | var |
js-console | off | console.log and console.debug |
Onion lints
These run only for an app with scripts = false in [package.metadata.wisp]. They read the shell, the templates, the Markdown pages, src/fonts.txt and the CSS in src/ and static/. They find what the browser loads from another host (No Script at All).
| Code | Level | Finds |
|---|---|---|
onion-fetch | error | a src, srcset, poster, <object data>, href or xlink:href of <use> and <image>, <link href>, imagesrcset, CSS url() or @import, or fonts.txt line that loads from another host |
onion-form | warn | a <form action> or formaction that posts to another host |
Fixes
wisp check --fix makes only the fixes that cannot change what the page means: a redundant role, a debugger statement, an empty CSS rule and a CSS declaration that repeats the one before it. It writes each file whole (a temporary file with a name of its own, then a rename: it deletes no file of yours), keeps the byte order mark and the line ends, skips a file with mixed line ends or a file that is not UTF-8 text, and never writes through a symbolic link. A duplicate CSS declaration is fixed only when nothing but white space stands between the two. After 8 rounds of fixes in a file, it says when fixes are left: run it again. If a write fails, it lists the files that it wrote before. A second run changes nothing, unless the output says that fixes are left. A rule at off is not fixed. wisp check --fix --dry-run writes nothing, names the files, and fails if one would change (for CI). It is an error with --rust, --types, --target or --explain-imports, because it stops after the fixes.
SEO lints
Same commands, for the pages that the sitemap lists. The lint reads a page and its layouts together. <!-- wisp-ignore seo-title --> silences a lint for the file. The lint skips noindex, (private) and guarded pages.
seo-title: missing, duplicate, empty, or literal text outside 10 to 60 characters.seo-description: missing (a<title description="…">counts), duplicate, or literal text outside 50 to 160 characters.seo-canonical: aconst PRERENDERpage with no<link rel="canonical">(or{@html wisp::alternates(cx)}) whileSITE_URLorORIGINis set.seo-h1: no<h1>, or more than one.seo-link:<a href="/x">to a path nothing answers (code spans and blocks of a.mdpage are not read); inwisp build --static, a link indist/to a missing file.seo-anchor: inwisp build --static,href="/page#id"with no suchid. The build crawl also fails on it (error /page links to /x#id, but no element has the id id), unless--allow-dead-links. An id that only JS makes fails the build: add the id in the server HTML, or build with--allow-dead-links.
Client router
The client API (beforeNavigate, afterNavigate, onNavigate, preloadData, preloadCode, invalidate(key), updated) and the link attributes data-wisp-noscroll, -keepfocus and -replacestate live in wisp.js and live.js. wisp:navigate is cancelable, wisp:leave collects what onNavigate waits for, wisp:preload reuses the hover prefetch. depends goes in the browser's +page.js load.
Navigation moves focus to the <h1> and announces the title in an aria-live region. Motion respects prefers-reduced-motion. Dialog and Menu use native <dialog> and popover, and Input, Textarea and Select set aria-invalid and aria-describedby. Phones: The router and forms.
Template syntax, components, snippets and scoped styles: Template syntax and styles.
Is This Page Useful?