Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Laterite

Laterite is a content management framework for Rust: an admin panel from descriptors, themes edited in the admin, a media library, plugins, users and permissions, migrations and typed settings, on PostgreSQL, MySQL or SQLite.

cargo install laterite-cli
lat new
CrateProvides
laterite-coreConfig, errors, the database layer, migrations, modules.
laterite-authBackend users, sessions, roles and permissions.
laterite-adminThe admin router, list and form screens, settings.
laterite-mediaContent-addressed file storage. Optional.
laterite-webStatic-site generation and page metadata. Optional.
laterite-cliThe lat command.
laterite-macrosThe t!, tn! and tp! translation macros.
SectionCovers
Getting StartedInstall, run, deploy and upgrade an application.
ConfigurationEvery key in the configuration files.
Admin PanelUsers, permissions, navigation, branding, settings and logs.
Forms, Lists, ElementsScreens from descriptors, and every field, column and filter type.
Plugins, Screens and RoutesModules of your own and the screens they mount.
Database, Services, MediaMigrations, queries, events, sessions, search and files.
Themes and MarkupThe site’s templates and the template language.
ReferenceBehaviours, the command line, icons and the API documentation.

Not in the framework today: mail, queues, a scheduler, a cache driver, an encryption service, multi-site.

Installation

lat new scaffolds a project, sets up the database and creates the first administrator.

Install the CLI

cargo install laterite-cli

Requires stable Rust and one of PostgreSQL, MySQL/MariaDB or SQLite.

Create an application

lat new
cd acme
cargo run          # or: lat serve

Open http://127.0.0.1:8080/admin and sign in.

lat new asks for:

PromptValue
What are you building?An application with an admin panel, or a static website (see Static Website).
Application nameAny text, such as Acme Blog. Its slug, acme-blog, names the crate, directory and database.
Where does the site’s content live?Static website only: files you edit, a folder the admin writes, a folder the admin commits (git), or a database.
Site URLStatic website only: the origin canonical links use.
Display timezoneAn IANA name; type to search.
Listen addresshost:port. Default 127.0.0.1:8080.
DatabasePostgreSQL, MySQL/MariaDB or SQLite, and its connection details. Offers to create the database. A folder or git site uses SQLite without asking.
First administratorUsername, email, password. Not asked for a site of files you edit.

Every prompt has a flag: --static, --content, --url, --timezone, --listen, --admin with --admin-email, --admin-name and the password in LAT_NEW_ADMIN_PASSWORD. A script runs lat new without a terminal.

Serve

lat serve
lat serve --port 3000
lat serve --host 0.0.0.0
lat serve --listen 0.0.0.0:3000

Runs from anywhere inside the application. An override sets <PREFIX>__SERVER__LISTEN; see Application and Server.

See what it generates

The layout, main.rs, the module file and the configuration files: Directory Structure.

Set the brand

[app]
name = "Acme Blog"

Shown across the admin. Branding overrides it; with both blank the brand is Laterite.

Check the setup

lat doctor

Verifies the configuration, the timezone, write access to storage/, the database connection and the framework tables. Exits non-zero on any failure.

Manage administrators

lat admin create editor --email editor@acme.test --first-name Editor
lat admin reset-password editor

Both prompt for a password; --generate prints a strong one that must be changed at first sign-in. Outside the application, pass --database-url or set DATABASE_URL. A fresh install with no accounts serves a first-run setup screen at /admin.

Static Website

lat new scaffolds a static website as a theme folder: pages, layouts, partials, content and assets, with no database and no Rust project.

lat new "Acme" --static
cd acme
lat serve          # http://127.0.0.1:8080, rebuilt on every change
lat theme build    # dist/

lat new without --static asks first:

PromptValue
What are you building?An application with an admin panel, or a static website.
Where does the site’s content live?In this folder as files you edit (--content files, what --static alone means); in this folder, edited in the admin (folder); in this folder, committed by the admin (git); in a database with the admin beside it (database).
Application nameAny text; its slug names the folder and the theme.
Site URLThe origin canonical links use.
Database, Build hook URLFor database: the connection, and the host’s hook (blank to set later).
First administratorFor every choice but files: username, email, password.
lat new "Acme" --static --content git
cd acme
lat serve                     # the admin at http://127.0.0.1:8080/admin, the site beside it
lat make:resource article --field title:text --source content/articles --format markdown --git
git remote add origin git@github.com:acme/site.git
lat theme publish             # push the commits the admin made
lat theme build               # dist/, as the host does on push

A site whose content is edited in the admin is an application whose build is static: it carries the Cargo project, src/main.rs with the theme module, the framework’s own tables in storage/site.db (or the database named), and the theme folder. A folder or git site also carries its first plugin, plugins/site-plugin, with a post collection kept as records in files under content/posts/, the posts component the theme reads it through, and the pages /posts and /posts/:slug built per record. Folders named in theme.copy are served by lat serve as the build copies them. lat serve runs its admin; lat theme build renders dist/; lat theme publish pushes (git) or calls the build hook (database). Default https://<slug>.example.

See what it generates

acme/
├── config/default.toml        # [app] name, url; [theme] folder, copy
├── themes/acme/
│   ├── theme.yaml
│   ├── layouts/default.htm
│   ├── pages/home.htm         # url: /
│   ├── pages/about.htm        # url: /about
│   ├── pages/404.htm
│   ├── partials/nav.htm
│   ├── content/intro.md
│   └── assets/css/site.css
├── build.sh                   # installs lat, runs the build
├── netlify.toml
└── README.md

A page carries its settings as front matter above the markup:

---
url: /about
layout: default
title: About
description: Who we are and what we do.
---
<h1>{{ this.page.title }}</h1>
<p>{{ this.page.description }}</p>

The settings and the template language are those of a theme in an application: Pages, Layouts and Partials, Content, Templating.

Set the config

[app]
name = "Acme"
url = "https://acme.example"

[server]
listen = "127.0.0.1:8080"

[theme]
folder = "themes/acme"
copy = ["static:static"]
KeyDefaultMeaning
app.urlThe origin canonical links use.
server.listen127.0.0.1:8080The preview’s address.
theme.folderThe theme folder, relative to the project; its name is the theme’s code.
theme.copy[]Directories copied into the output, <src>:<dest>, relative to the project. A source absent on this machine is skipped with a note; a --copy flag’s is required.

Preview

lat serve
lat serve --port 3000
lat theme serve --from themes/other

Every request rebuilds the site when a file under the folder changed; a template that does not compile shows its error in the browser.

Build and deploy

lat theme build
lat theme build --out public --base-url https://acme.example
lat theme build --from themes/other --copy docs/book:docs
FlagDefaultMeaning
--from <DIR>theme.folderThe theme folder.
--out <DIR>distThe output directory.
--base-url <URL>app.urlThe origin canonical links use.
--copy <SRC>:<DEST>theme.copyA directory copied into the output at <DEST>. Repeatable, added to the config’s.

build.sh runs the same build on a host that starts from nothing:

cargo install laterite-cli --locked
lat theme build --out dist

netlify.toml points Netlify at it and serves dist/.

Choose where the content lives

[theme]
folder = "themes/acme"
source = "folder"
SourceThe theme isEditedPublished
databasethe rows in [database]in the adminlat theme publish calls theme.publish.hook
folderthe theme folderin your editor, or in the admin, which writes the filescommit the folder
gitthe theme folderin the admin, which commits every savelat theme publish pushes
a module’sits ownits ownits own

folder and database are always available; git needs the theme-git feature:

lateritecmf = { version = "0.12", features = ["sqlite", "theme-git"] }
[theme]
folder = "themes/acme"
source = "git"

[theme.git]
remote = "origin"
branch = "main"

[theme.publish]
hook = "https://api.netlify.com/build_hooks/..."
KeyDefaultMeaning
theme.sourcedatabaseThe source by code.
theme.git.remote, theme.git.branchorigin, mainWhere publish pushes.
theme.publish.hooknoneA URL lat theme publish posts to after the source published; the host rebuilds on it.

A file-backed source is read in before every build, and every save in the admin is written back. The framework’s own tables (users, sessions, settings, logs) stay in [database].

Keep media with the site

[media]
folder = "public/media"

Uploads land in the folder, a git site commits each one, and the build writes every file and its variants under dist/storage/media/. See Admin configuration.

Edit from a laptop

cargo build --release
./target/release/acme admin

admin serves the application and opens the admin in the browser. With a folder or git source and records in files, every save lands in the checked-out repository; push it to publish.

CommandDoes
acme or acme serveServes the admin and the site on server.listen.
acme adminThe same, and opens /admin in the browser.
acme buildRenders dist/.
acme publishPushes, or calls the build hook.

Add a plugin

lat plugin add https://github.com/rainmill/discovery-plugin
lat new "Acme" --static --plugin ../discovery-plugin

The first plugin gives the site a Cargo project (Cargo.toml, src/main.rs, plugins/); lat serve and lat theme build run that binary from then on, and the plugin takes part in the build. A plugin a static website can use declares it in its manifest:

[package.metadata.laterite]
plugin = "rainmill.discovery"
static = true

A plugin without static = true is refused at install; one whose module answers supports_static false stops the build, by name. A plugin’s definitions live under plugins/<module id>/:

acme/
├── plugins/
│   ├── plugins.toml
│   └── rainmill.discovery/
│       ├── robots.yaml
│       └── sitemap.yaml
├── src/main.rs
└── Cargo.toml
# plugins/rainmill.discovery/robots.yaml
groups:
  - agents: ["*"]
    disallow: ["/drafts/"]

What each plugin reads is on its own page; the discovery plugin writes robots.txt and a sitemap.xml of every page the build wrote.

Move to an application

cd themes && zip -r ../acme.zip acme && cd ..
lat new "Acme"
cd acme && lat theme import acme ../acme.zip

The folder is the theme’s export layout: the same files become the application’s theme. See Export and Import.

Directory Structure

lat new generates an application in this layout.

acme/
├── Cargo.toml
├── README.md
├── .gitignore
├── config/
│   ├── default.toml     # committed defaults
│   └── local.toml       # git-ignored; the database URL
├── plugins/
│   └── plugins.toml     # the installed plugins
├── plugins-manifest/    # generated by `lat plugin sync`
├── src/
│   ├── main.rs
│   └── migrations/      # the application's module and its migrations
└── storage/             # runtime data; git-ignored
PathHolds
Cargo.tomlThe application crate and the workspace its plugins join.
config/The layered configuration. See Application and Server.
plugins/Installed plugin crates and the list that names them. See Installing Plugins.
plugins-manifest/The generated crate that links the listed plugins. Never edited by hand.
src/main.rsThe entry point.
src/migrations/The application’s module and its migrations. See Migrations.
storage/Files the application keeps while it runs. backend.storage moves it.

Read main.rs

[dependencies]
lateritecmf = { version = "0.12", features = ["postgres"] }
laterite-core = "0.12"
plugins-manifest = { path = "plugins-manifest" }
use lateritecmf::prelude::*;

mod migrations;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    Bootstrap::new("config")
        // Every plugin under plugins/, as listed in plugins/plugins.toml.
        .modules(plugins_manifest::all())
        .module(migrations::AppModule)
        // .extend(|router, ctx| router.merge(my_api(ctx.db())))
        .run()
        .await
}
CallDescription
Bootstrap::new("config")The configuration directory, relative to the working directory.
.modules(..)The installed plugins.
.module(..)The application’s own module.
.extend(..)Merges the application’s own routes onto the admin router.

Read the module

src/migrations/mod.rs defines the application’s module:

use lateritecmf::prelude::*;

migration_set! {
    module_id: "acme",
}

pub struct AppModule;

impl Module for AppModule {
    fn id(&self) -> ModuleId {
        ModuleId::new(MODULE_ID)
    }
    fn migrations(&self) -> MigrationSet {
        migrations()
    }
}

lat make:migration <description> adds a file to the directory and lists it in the migration_set! block. The methods a module may add are in Writing a Plugin.

Read the configuration

# config/default.toml
[app]
name = "Acme Blog"
env_prefix = "LAT"
# url = "https://acme.example"

[server]
listen = "127.0.0.1:8080"

[backend]
timezone = "UTC"
secure_cookie = false
# path = "/admin"
# config/local.toml
[database]
url = "postgres://localhost/acme"

Every key is in Configuration.

Development Workflow

Two local conveniences: a .test domain per application and a rebuild that keeps the browser connected.

Use a local domain

lat domain routes every host under a reserved .test TLD to loopback. macOS, built on dnsmasq.

brew install dnsmasq
lat domain setup

setup writes a dnsmasq wildcard rule and /etc/resolver/test, prompting for sudo. It is idempotent.

FlagDescription
--dry-runPrint the plan and change nothing.
--tld <name>Use a different reserved TLD.

Open an application by name

lat serve --port 8080
# http://acme.test:8080/admin

Set app.url to match:

[app]
url = "http://acme.test:8080"

The port stays in the URL. HTTPS on the bare name is a reverse proxy’s job.

Status and teardown

lat domain status
lat domain teardown

teardown removes only what lat domain created. A .test managed by another tool is detected: setup adds nothing and teardown leaves it alone.

Reload on change

systemfd holds the port and watchexec rebuilds on change; the browser reconnects after every edit.

cargo install systemfd
brew install watchexec   # or cargo install watchexec-cli

Reuse the passed socket

Add listenfd and take the socket in main:

use listenfd::ListenFd;
use tokio::net::TcpListener;

let listener = match ListenFd::from_env().take_tcp_listener(0)? {
    Some(std_listener) => {
        std_listener.set_nonblocking(true)?;
        TcpListener::from_std(std_listener)?
    }
    None => TcpListener::bind("127.0.0.1:8080").await?,
};
axum::serve(listener, app).await?;

None is the normal path: cargo run and production bind directly.

Run the loop

systemfd --no-pid -s http::8080 -- \
    watchexec -r -e rs,html,css,toml -- \
    cargo run -p acme

.html and .css are watched too: templates and the stylesheet are compiled in. As a justfile recipe:

dev:
    systemfd --no-pid -s http::8080 -- \
        watchexec -r -e rs,html,css,toml -- \
        cargo run -p acme

See errors as you type

cargo install bacon   # or brew install bacon
bacon clippy

Deployment

Running an application in production: a release binary, the files beside it, secrets from the environment, and a reverse proxy in front.

Build the binary

cargo build --release
# target/release/acme

Run it from a directory holding config/.

Ship the files

PathDescription
acmeThe release binary. Plugins are compiled into it; nothing of plugins/ ships.
config/default.tomlThe committed defaults.
config/production.tomlOptional. Read when APP_ENV=production.
storage/Writable by the process. Empty on the first start.

config/local.toml stays on the development machine. Secrets travel as environment variables.

Set secrets in the environment

export APP_ENV=production
export LAT__DATABASE__URL="postgres://acme:secret@db.internal/acme"
export LAT__APP__KEY="$(lat key generate --print | head -1)"
./acme
VariableSets
APP_ENVWhich config/<APP_ENV>.toml layer is read. Default development.
<PREFIX>__DATABASE__URLdatabase.url.
<PREFIX>__APP__KEYapp.key, the key everything is sealed and signed under. Set it in production; several instances share it. See Encryption and Signing.
<PREFIX>__SECTION__KEYAny other key. The prefix is app.env_prefix, LAT by default.

Sit behind a proxy

# config/production.toml
[app]
url = "https://acme.example"

[server]
listen = "127.0.0.1:8080"

[backend]
secure_cookie = true
trusted_proxies = ["127.0.0.1/32"]
KeyDescription
app.urlThe public origin absolute links build on.
backend.secure_cookieSets the Secure flag on cookies. true behind HTTPS.
backend.trusted_proxiesCIDR ranges whose X-Forwarded-For is read. The proxy’s own network.
server {
    listen 443 ssl;
    server_name acme.example;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Gate the deploy

lat doctor
CheckPasses when
Configuration loadsEvery layer parses and database.url is present.
Timezone is validbackend.timezone is an IANA name.
storage/ is writableThe process can write the application’s storage/.
Database is reachableA connection opens.
Tables existThe framework’s tables are migrated.
plugins-manifest is in syncThe list and the generated crate agree.
Descriptor files parseEvery YAML descriptor loads.

Exits non-zero on any failure. Run it from the application directory, or pass --database-url.

Recover access

lat admin create ops --email ops@acme.example --first-name Ops --generate
lat admin reset-password editor --generate
lat admin unlock editor
lat admin purge
CommandDescription
createA new superuser. --generate prints a strong password.
reset-passwordA new password for an existing user.
unlockClears a user’s failed sign-in lockout.
purgeRemoves expired sessions and stay-signed-in credentials.

Outside the application directory, pass --database-url or set DATABASE_URL.

Upgrading

Moving an application to a newer framework version.

Read the changelog

The crates release together under one version. Read the version’s section of CHANGELOG.md before bumping.

BumpBefore 1.0
Patch, 0.9.19 to 0.9.20Additive or a fix. No code changes.
Minor, 0.11 to 0.12May break. The section lists what moved.

Bump the requirements

Every laterite-* and lateritecmf requirement moves together.

# Cargo.toml
[workspace.dependencies]
lateritecmf = { version = "0.12", features = ["postgres"] }
laterite-core = "0.12"
laterite-admin = "0.12"
# plugins/<folder>/Cargo.toml, for each plugin the application owns
[dependencies]
laterite-core = "0.12"
laterite-admin = "0.12"
CrateDescription
lateritecmfThe umbrella an application depends on.
laterite-coreConfiguration, migrations, modules, queries.
laterite-adminThe admin panel.
laterite-authSign-in, sessions, permissions.
laterite-mediaThe media library.
laterite-webThemes and public pages.
laterite-macrosThe translation-string macros.
laterite-cliThe lat command.
cargo install laterite-cli
cargo update
cargo build --release

A patch needs cargo update alone; the requirement already admits it.

Run the migrations

lat serve

Starting the application applies the framework’s new migrations, then the application’s and the plugins’.

Check the result

lat doctor

Third-Party Notices

A built binary carries the licence notices of everything compiled into it.

Distribute source or a crate

Nothing to do: licence files travel inside each package.

Distribute a binary

Generate a notice with cargo about and ship it beside the binary:

cargo install cargo-about
cargo about init          # writes about.toml and about.hbs
cargo about generate about.hbs > NOTICE.html

It reads every dependency’s NOTICE, LICENSE and COPYING, Laterite’s bundled fonts and icons included.

What Laterite bundles

WorkLicence
IBM Plex Sans, IBM Plex MonoSIL Open Font License 1.1
Space GroteskSIL Open Font License 1.1
Lucide, a subsetISC, with an MIT annex for icons derived from Feather
htmxZero-Clause BSD

Full texts: crates/admin/NOTICE.

Application and Server

Configuration is layered: one build runs across environments without code changes. This page covers the layers, [app] and [server].

Layer the files

Later layers override earlier ones.

LayerSource
1default.toml. Required.
2<APP_ENV>.toml. Optional. APP_ENV defaults to development.
3local.toml. Optional; keep it out of version control.
4<PREFIX>__SECTION__KEY environment variables, e.g. LAT__DATABASE__URL. The prefix is LAT unless app.env_prefix names another.
SectionPage
[database]Database
[backend]Admin
[auth]Authentication

Set [app] and [server]

[app]
name = "Acme Blog"               # baseline admin brand
env_prefix = "LAT"               # prefix of the overriding environment variables
locale = "en"                    # default admin language
debug = false                    # error pages show the cause
# url = "https://acme.example"   # public base URL; derived from listen when unset

[server]
listen = "127.0.0.1:8080"
KeyDescription
app.nameThe application name, the baseline admin brand. Branding overrides it. Default Laterite.
app.urlThe public base URL absolute links build on, scheme and host with any port. Derived from server.listen when unset.
app.localeDefault admin UI language, a BCP 47 tag. Default en. See Localization.
app.debugError pages include the cause. Off by default. See Errors and Logging.
app.env_prefixThe prefix of the overriding environment variables. Default LAT.
app.keyThe application key, id:<base64 of 32 bytes>; lat key generate writes one. See Encryption and Signing.
app.previous_keysKeys retired by a rotation, each id:<base64>, read but never written with.
server.listenThe host:port to bind. Default 127.0.0.1:8080. lat serve --host, --port and --listen override it.

Set [cache]

[cache]
store = "auto"            # auto | null | memory | redis
memory_mib = 64
poll_seconds = 2
# url = "redis://127.0.0.1:6379/0"
KeyDescription
cache.storeauto is null while app.debug is on and memory otherwise. See Cache.
cache.memory_mibThe memory store’s capacity. Default 64.
cache.poll_secondsHow often a process reads the other processes’ invalidations; 0 for a single process. Default 2.
cache.urlThe Redis URL for the redis store.
cache.prefixThe prefix of every Redis key. Default laterite.

Set [queue]

[queue]
store = "auto"            # auto | database | redis
mode = "worker"           # worker | external | inline
workers = 2
queues = ["default"]
retry_after_seconds = 90
KeyDescription
queue.storeWhere jobs wait; auto is database. See Queue.
queue.modeworker in the application process, external for queue work alone, inline to run a job as it is pushed.
queue.workersWorkers per process in worker mode. Default 2.
queue.queuesThe queues taken from, in priority order. Default ["default"].
queue.retry_after_secondsWhen a claimed job counts as abandoned. Default 90.
queue.poll_secondsAn idle worker’s wait. Default 1.

Set [schedule]

[schedule]
mode = "ticker"           # ticker | external | off
KeyDescription
schedule.modeticker in the application process, external for schedule run alone, off for none. See Scheduler.

Set [mail]

[mail]
driver = "smtp"            # smtp | log | stub
from = "Acme <no-reply@acme.example>"

[mail.smtp]
host = "smtp.acme.example"
port = 587
encryption = "starttls"
username = ""
password = ""
KeyDescription
mail.driversmtp, log or stub; the Mail settings screen lays over it. See Mail.
mail.fromThe sender, Name <address>.
mail.toA development override for every recipient.
mail.smtp.*host, port, encryption (starttls, tls, none), username, password, timeout_seconds.

Set [theme]

[theme]
folder = "themes/acme"
copy = ["static:static"]
KeyDefaultMeaning
foldernoneA static website’s theme folder, relative to the project. Set, lat serve previews it and lat theme build renders it. See Static Website.
copy[]Directories copied into the build output, <src>:<dest>, relative to the project; one absent on this machine is skipped with a note.
sourcedatabaseWhere the theme lives: database, folder, git (feature theme-git), or a code a module registered.
git.remote, git.branchorigin, mainWhere the git source pushes on publish.
publish.hooknoneA build hook URL publish posts to.

Mount a module’s screens

A module’s screens namespace under its identity: acme.places contributing /nodes serves /admin/acme/places/nodes. A module may declare a shorter base; backend.paths has the last word.

Locate the application from lat

lat walks up from the current directory to the nearest config/default.toml and reads the application’s prefix from it. lat admin takes the database URL from --database-url, then DATABASE_URL, then database.url.

Find what is not configured here

SettingWhere
Branding: name, colour-mode default, logoBranding
Preferences: a user’s own timezonePreferences. See Dates and Timezones.

Database

[database] names the connection.

[database]
url = "postgres://localhost/acme_dev"
max_connections = 10             # optional
acquire_timeout_secs = 5         # optional
KeyDescription
urlThe connection URL. Required.
max_connectionsThe pool ceiling. Default 10.
acquire_timeout_secsSeconds to wait for a pooled connection. Default 5.

Choose the driver

DatabaseURLFeature
PostgreSQLpostgres://user:pass@host/acmepostgres
MySQL / MariaDBmysql://user:pass@host/acmemysql
SQLitesqlite://storage/database.db?mode=rwcsqlite
[dependencies]
lateritecmf = { version = "0.12", features = ["postgres"] }

Keep the URL out of version control

# config/local.toml, git-ignored
[database]
url = "postgres://localhost/acme_dev"
LAT__DATABASE__URL="postgres://acme:secret@db.internal/acme" ./acme

Give lat the URL

lat admin list --database-url postgres://localhost/acme_dev
DATABASE_URL=postgres://localhost/acme_dev lat admin list
SourceOrder
--database-urlFirst.
DATABASE_URLSecond.
database.url of the application found from the current directory upwardLast.

Admin

[backend] configures the admin panel. Every key is optional.

[backend]
secure_cookie = false            # true behind HTTPS
timezone = "UTC"                 # default display timezone, IANA name
path = "/admin"                  # where the admin mounts
trusted_proxies = []             # CIDR ranges whose X-Forwarded-For is believed
storage = "storage"              # where files the admin keeps go
secret = "a-long-random-string"  # signs timed URLs
skin = "standard"
upload_extensions = []
origin_check_except = ["/webhooks/*"]

[backend.order]
"backend.nav" = ["dashboard", "acme.shop", "media", "settings"]

[backend.menu]
"backend.access_log" = { in = "backend.nav", slot = "tools" }

[backend.paths]
"acme.places" = "/places"          # a whole module's screens
"acme.places/nodes" = "/places"    # one screen; the more specific key wins

Set the keys

KeyDescription
secure_cookieSets the Secure flag on cookies and sends Strict-Transport-Security (one year, subdomains included). true behind HTTPS.
timezoneDefault display timezone until a user picks their own. See Dates and Timezones.
pathURL path the admin mounts under.
trusted_proxiesCIDR ranges. X-Forwarded-For is read only from a peer inside one. Empty records the peer address.
pathsRemounts a module’s screens, or one screen, at another path. Two claims on one path abort the boot.
upload_extensionsThe file extensions an upload may carry, lowercased. Empty applies the default list (images, documents, audio, video, fonts, archives). See Media Library.
origin_check_exceptPaths a POST from another site may reach: an exact path, or a prefix ending in *. Only for endpoints that authenticate each request themselves. See Public Routes.
skinThe admin skin by code: standard (default), compact, or one a module registered. See Skins.
storageThe directory files the admin keeps go under, relative to the working directory unless absolute. Uploaded import files go to private beneath it.

Keep the media library in the project

[media]
folder = "public/media"
KeyDefaultMeaning
media.foldernoneA folder of the project the library stores its files in. Unset, the library uses <backend.storage>/media. With [theme] source = "git", every stored or removed file is committed.

A static build writes every file and variant under dist/storage/media/, at the paths the pages link to. order | Arrangement overrides by hierarchy: "backend.nav", "backend.nav.<section>", "backend.settings" or a plugin’s own, each a list of keys in the wanted order. See Navigation. menu | Entries moved out of their home, keyed by entry: { in, slot, order, category }. See Navigation. secret | The key timed URLs are signed with (a private file’s). Set it when several instances share one database.

Authentication

[auth] sets session lifetimes, sign-in lockouts and the password policy. Every key is optional.

[auth]
session_idle_timeout_secs = 7200      # 2h
session_absolute_timeout_secs = 43200 # 12h
remember_duration_secs = 1209600      # 14d
max_failures = 5
max_failures_per_address = 20
failure_window_secs = 900
access_log_retention_days = 365

[auth.password_policy]
min_length = 8

Set the keys

KeyDescription
session_idle_timeout_secsQuiet time before a session ends, from the last request. Default 7200.
session_absolute_timeout_secsCeiling from login, never extended. Default 43200. The earlier name session_ttl_secs is still read.
remember_duration_secsHow long an unused “stay signed in” credential lasts, from its last use. Default 1209600.
max_failuresFailed sign-ins from one address for one username before that address is locked out of it. Default 5.
max_failures_per_addressFailed sign-ins from one address, any username, before the address is locked out. Default 20.
failure_window_secsWindow the failures are counted over. Default 900.
access_log_retention_daysDays of the access log the hourly purge keeps. Default 365; 0 keeps every row.
password_policy.min_lengthThe shortest password accepted, wherever one is set. Default 8.

Clear a lockout

lat admin unlock editor

Dates and Timezones

Timestamps are stored in UTC and converted to a display timezone when rendered.

Display a timestamp

use laterite_admin::list::ListColumn;

ListColumn::new("created_at", "Created").datetime();
ListColumn::new("published_on", "Published").date();
ListColumn::new("is_active", "Active").yes_no();
KindRendered as
textThe stored value. Default.
datetime14 Aug 2026, 15:53, in the viewer’s timezone.
dateThe date, in the viewer’s timezone.
timeThe time, in the viewer’s timezone.
yes_noYes or No.

A value that does not parse is shown as stored.

Choose the timezone

Resolved per request:

  1. The user’s own preference, set under Preferences.
  2. Otherwise backend.timezone, an IANA name such as Asia/Kolkata. Defaults to UTC.

“Use the deployment default” in Preferences clears the user’s choice.

Errors and Logging

Admin handlers return Result<_, laterite_admin::AdminError>; the log follows RUST_LOG.

VariantStatusPage
NotFound404Not found
Forbidden403Forbidden
Internal(_)500Something went wrong

Map a domain error

async fn edit(state: &AdminState, id: &str) -> Result<Response, AdminError> {
    let row = fetch(state, id)
        .await?                        // CoreError::NotFound -> 404, DB error -> 500
        .ok_or(AdminError::NotFound)?; // a missing row -> 404
    Ok(render(view(row)))
}
FromTo
CoreError::NotFound404
CoreError::Forbidden, CoreError::Unauthorized403
AuthErrorThrough CoreError, the same mapping
A database error, a render failure, a panic500

An unmatched admin URL renders the 404 page.

Show the cause in development

[app]
debug = true   # off by default

A 500 logs its cause through tracing::error! in every mode. With debug on, the page shows it too. See Application and Server.

Configure logging

RUST_LOG=debug lat serve
RUST_LOG=info,laterite_admin=debug ./acme
VariableDescription
RUST_LOGA tracing filter directive. Unset, the filter is info,sqlx=warn.

An application that installs its own tracing subscriber before serve() keeps it.

Refuse a submission

A refused submission is not an AdminError: it answers 422 with the form re-rendered. See Validation.

Users and Roles

An operator is a person who signs in to the admin. Accounts are managed under Settings → Users → Administrators, gated by backend.manage_users; roles and what each holds are on Permissions. Every action on an account is on the audit log, named after the account it touched.

Create an operator from the command line

lat admin create editor --email editor@acme.test --first-name Editor --generate
lat admin reset-password editor --generate
lat admin list

--generate prints a strong password and marks it temporary; a typed or prompted password is the operator’s own.

Create an operator from code

use laterite_auth::NewOperator;
use laterite_core::Actor;

let id = auth
    .create_operator(
        NewOperator {
            username: "editor",
            email: "editor@acme.test",
            first_name: "Editor",
            last_name: None,
            password: &laterite_auth::password::generate(),
            timezone: None,
        },
        &Actor::user(admin.id, &admin.username),
    )
    .await?;
auth.require_password_change(id).await?;

let temporary = auth.reset_operator_password(id, &actor).await?;
auth.unlock("editor").await?;
CallDescription
create_operator(new, actor)A new account; the id is returned.
require_password_change(id)Marks the password temporary; the account replaces it at its next sign-in.
reset_operator_password(id, actor)A new temporary password, returned once; every device is signed out.
unlock(username)Clears a sign-in lockout.
create_superuserA superuser, the same way; first-run setup and lat admin create use it.

Invite an operator and reset a password

laterite.auth::invite   name, username, link, expires
laterite.auth::reset    name, username, link, expires
PageDoes
/admin/users/newCreates the account, shows the temporary password once, and mails laterite.auth::invite with a link to set a password; the link works for seven days.
/admin/forgotLinked from the sign-in page. Takes a username or email address and mails laterite.auth::reset with a link that works for one hour; the page says the same whether or not the account exists, and one address may ask five times in fifteen minutes.
/admin/set-password/<token>Opened from either link: a new password, checked against the password policy, then the sign-in page.

Both templates are edited under Settings → System → Mail Templates. The mail goes through the configured transport; with the log driver it sits in the Mail Log.

Groups

A group is a named set of accounts, for addressing people together. It grants no permissions. Groups are managed under Settings → Users → Groups, gated by backend.manage_groups, and ticked on an account’s page.

use laterite_auth::store;

let staff = store::create_group(&db, "staff", "Staff", Some("Everyone"), true).await?;
store::join_group(&db, user_id, staff).await?;
store::set_user_groups(&db, user_id, &[staff]).await?;

let mine = store::user_group_ids(&db, user_id).await?;
let members = store::group_member_ids(&db, staff).await?;
let id = store::group_id_by_code(&db, "staff").await?;
CallDescription
create_group(db, code, name, description, default)A new group; the id is returned. The code is stored lowercase.
list_groups(db)Every group, by name.
group_id_by_code(db, code)The id of the group with that code.
join_group(db, user, group)Adds one account.
join_everyone(db, group)Adds every account.
set_user_groups(db, user, groups)Replaces an account’s groups.
user_group_ids(db, user)The groups an account is in.
group_member_ids(db, group)The accounts in a group.

A group whose New accounts join this group is on is given to every account created afterwards; creating one on the Groups screen also adds every existing account.

Permissions

A permission is a dotted string such as posts.approve. A descriptor declares the one a screen requires; the framework checks it against the operator’s roles.

Register permissions

use laterite_admin::{Permission, ROLE_EDITOR};
use laterite_core::t;

registry.add_permission(
    Permission::new("acme.publish_pages", t!("Publish pages"), t!("Content"))
        .roles([ROLE_EDITOR]),
);

Registered permissions appear in the role editor under their group. Only a registered permission can be granted.

Rename a permission

Permission::new("acme.posts", t!("Manage posts"), t!("Content"))
    .renamed_from(["acme.manage.posts"])

At the next start every role and per-user override holding the old code is rewritten to the new one. Two permissions claiming one old code, or an old code still registered, abort the start.

Place a permission in a built-in role

RoleHolds
ROLE_ADMIN, AdministratorEvery permission that names no role, plus any naming it. The first operator holds it.
ROLE_EDITOR, EditorOnly the permissions that name it. Empty until your application registers some.

Permission::roles names the roles that hold a permission by default. Naming none means the administrator alone. Neither role is editable: duplicate one to make it yours.

Gate a screen

use laterite_admin::Resource;

registry.add_resource(
    Resource::new("/pages", "Pages", pages_list_config())
        .form(pages_form_config())
        .permission("acme.manage_pages"),
);
WhereEffect
Resource::permissionEvery route the resource mounts: 403 without the grant, the login screen when signed out. Unset leaves it open to any operator.
SettingsItem::permissionHides the item from the settings menu and refuses its form.
ScreenReg::new(path, permission, ..)Required. Enforced before the handler runs.
ToolbarButton::requireThe button is not rendered without the grant.
Shell::allows(code)In a module’s own handler: whether to show a control or answer 403.
Resource::create_permission, update_permission, delete_permissionOne write each, beside Resource::permission (below).

Gate each write

# descriptors/posts.yaml
permission: acme.posts
permissions:
  create: acme.posts.create
  update: acme.posts.update
  delete: acme.posts.delete
Resource::new("/posts", "Posts", list)
    .form(form)
    .permission("acme.posts")
    .create_permission("acme.posts.create")
    .update_permission("acme.posts.update")
    .delete_permission("acme.posts.delete")
KeyAsked for byWithout it
createThe New form and its saveNo New button; 403
updateA save, an editable cell, a move or reorder, a related record’s changeThe form opens read-only, with no Save; the section has no New; 403
deleteDelete, restore, delete permanentlyNo row selection or Delete; 403

An operator needs permission and the key’s grant. A key left out asks for permission alone. A key naming a permission no module registers aborts the start.

Match a grant

GrantCovers
posts.approveExactly posts.approve.
posts.*posts.approve, posts.tags.create; not the bare posts.
*Everything.

A superuser passes every check.

Resolve for one operator

  1. A superuser: allowed.
  2. The operator’s own override for that permission: Deny refuses, Allow grants.
  3. Otherwise the roles decide.

Roles and overrides are both set per user on the Administrators screen; Inherit is the default.

Grant a built-in permission

PermissionGrants
backend.manage_usersThe backend users list and per-user overrides.
backend.manage_rolesThe roles list and the role editor.
backend.manage_groupsThe groups list, a group’s form and its members.
backend.manage_pluginsThe plugins screen.
backend.view_audit_logThe audit log.
backend.view_access_logThe access log.
backend.view_request_logThe request log.

Navigation

A resource and a screen each add their own menu entry. A module adds sections and extra entries through its registry.

Add an entry

# descriptors/posts.yaml
menu: { under: acme.content, icon: file-text, order: 2 }
registry.add_nav(NavItem::new("acme.reports", "Reports", "/reports").permission("acme.reports"));

Resource::new("/posts", "Posts", list)
    .permission("acme.posts")
    .menu(Placement::new().under("acme.content").icon("file-text").order(2))

ScreenReg::new("/reports", "acme.reports", Arc::new(ReportsScreen))
    .in_menu("Reports")
    .menu(Placement::new().under("acme.content"))
menu keyDefaultDescription
underthe top barThe key of the section the entry sits under.
iconnoneAn icon name from the icon set.
slotapplicationThe band the entry belongs to (see below).
order0Sorts among siblings of the band, lowest first; equal orders sort by label.
after, beforenoneSits right after or before the sibling with that key, whatever the bands say. A resource’s key is resource: and its path (resource:/posts), a screen’s screen: and its path, a contributed item’s its own.
in_settingsnoneA Settings category heading (System): the entry is listed in Settings under it, with no menu entry.
descriptionnoneThe line under the label in Settings.
menu: falseMounts the routes with no menu entry.
SlotValueHolds
home0The dashboard.
content100What the site publishes.
media200The media library.
application500The application’s own screens: the default.
people700Accounts and roles.
tools800Reports, logs and tools.
system900Settings.
lasti32::MAXAfter everything.
NavItemDescription
NavItem::new(key, label, path)An entry leading to path under the admin mount.
NavItem::section(key, label)A tab holding entries; it leads to the first one the operator may open.
.icon(name), .order(n), .after(key), .before(key), .under(key), .permission(code)As the menu keys above; permission hides the entry from an operator without it.
.in_settings(category)Renders the entry in Settings under category (see below).
.description(text)The line under the label in Settings.

A resource’s entry carries the resource’s permission, a screen’s its own. A duplicate key, under naming a key nobody declared, or after and before naming no sibling, aborts the start.

Add a section

registry.add_nav(NavItem::section("acme.content", "Content").icon("folder").order(10));

Resource::new("/pages", "Pages", list)
    .menu(Placement::new().under("acme.content").order(1))

A section is a tab in the top bar. An operator sees only the entries they may open; a section with none left is not shown. Dashboard and Settings are always first and last.

Place a section in Settings

registry.add_nav(
    NavItem::section("acme.shop", t!("Shop"))
        .icon("store")
        .description(t!("Products, orders and invoices."))
        .slot(slot::SYSTEM)
        .in_settings(t!("Shop")),
);
# descriptors/products.yaml
menu: { under: acme.shop, order: 1 }
# descriptors/orders.yaml
menu: { under: acme.shop, order: 2 }
PlacedRenders
A sectionOne settings item linking to its first entry; each entry’s list shows the entries as tabs.
An entryA settings item linking to its page.
A tab the operator lacks the permission forLeft out of the tabs.

A deployment’s [backend.menu] move places a section the same way, or puts a module’s settings section back in the top bar with its entries in the sidebar:

[backend.menu]
"acme.shop" = { in = "backend.settings", category = "Shop" }
"rainmill.pdf" = { in = "backend.nav" }

Order a hierarchy

[backend.order]
"backend.nav" = ["dashboard", "acme.shop", "media", "settings"]
"backend.nav.acme.content" = ["resource:/pages", "resource:/posts"]
"backend.settings" = ["backend.branding", "web.themes"]
HierarchyKeysPinned
backend.navThe top bar’s entries.dashboard first, settings last.
backend.nav.<section>A section’s entries.none
backend.settingsSettings items by code.none

A key left out keeps its arrangement after the listed ones; a key that is no entry is skipped.

A hierarchy of your own takes the same [backend.order] key:

use laterite_core::arrange::{arrange, Arranged, Hierarchy, Overrides, Policy, Position, slot};

let widgets = arrange(
    &Hierarchy::new("acme.dashboard").policy(Policy::Fixed),
    widgets,
    Overrides { deployment: config.order.get("acme.dashboard").map(Vec::as_slice), operator: None },
)?;
Hierarchy builderDescription
new(key)The key [backend.order] names.
policy(Policy::Fixed)Renders the declared arrangement; overrides are logged and ignored. Adjustable is the default.
operator_adjustable()Lets an operator’s preference rearrange it too.
pin_first(key), pin_last(key)Keys that hold the ends whatever anyone says.

Move an entry

[backend.menu]
"backend.access_log" = { in = "backend.nav", slot = "tools" }
"resource:/orders" = { in = "backend.settings", category = "Shop", order = 5 }
"screen:/reports" = { in = "backend.nav.acme.content" }
[backend.menu] keyMeaning
The entryA menu key (resource:/orders, screen:/reports, a contributed item’s key) or a settings item’s code.
inbackend.nav, backend.nav.<section> or backend.settings.
slot, orderThe band and order there; the entry’s own when left out.
categoryThe settings heading; the band’s name when left out.

A moved entry keeps its label, icon, permission and target: a resource moved into settings opens at its own path with the settings sidebar beside it, and a settings item moved into the top bar is a tab. A section moved into settings is one item with its entries as tabs.

Register a palette source

# descriptors/posts.yaml
palette: acme.posttitles
Resource::new("/posts", "Posts", list).palette("acme.posttitles")
KeyDescription
paletteA registered picker source. The command palette (Ctrl+K, Cmd+K) finds this resource’s records through it and opens each at its edit page. Absent keeps the records out.

Branding

Settings › Branding, saved by a user with backend.manage_branding. A blank name keeps app.name.

Set the fields

FieldTakesEffect
Application nametextthe brand in the top bar, drawer, sign-in page and titles; blank keeps app.name
Logoa library imageshown in place of the mark
Navigation logoa library imageshown in the top bar and drawer; blank uses the logo
Browser icona library imagethe tab icon
Accent colour#rrggbb--accent, its pressed shades and tints, and link colours
Colour modeauto, light, darkwhat a user sees before choosing their own
Sign-in prompttextthe line above the sign-in form
Sign-in taglinetextthe line on the panel beside the form
Sign-in backgrounda library imagebehind that panel
Show the panelon, offoff leaves the form alone, centred
Custom stylesheetCSSadded to every admin page; @import, scripts and closing tags are removed

Each image is a public media field: the picker takes public files alone. See Storage Disks.

Skins

A skin is a stylesheet layered after the framework’s own, selected per deployment by backend.skin.

Select a skin

# config/default.toml
[backend]
skin = "compact"
CodeShips withStylesheet
standardthe frameworknone
compactthe frameworktighter spacing, smaller controls, a narrower sidebar

Contribute a skin

use laterite_admin::skin::Skin;
use laterite_admin::{AdminAsset, AdminRegistry};
use laterite_core::t;

fn register(registry: &mut laterite_core::Registry) {
    registry.add_asset(
        "acme/dense.css",
        AdminAsset::css(include_bytes!("../assets/dense.css")),
    );
    registry.add_skin(Skin {
        code: "acme.dense",
        label: t!("Dense"),
        stylesheet: Some("acme/dense.css"),
    });
}
/* assets/dense.css */
:root[data-lat-skin="acme.dense"] {
  --card-pad: 10px;
  --control-h: 32px;
  --sidebar-w: 220px;
}
[data-lat-skin="acme.dense"] .lat-table td {
  padding: 6px 10px;
}
FieldValue
codeSelected by backend.skin. A module’s carries its vendor: acme.dense.
labelThe skin’s name.
stylesheetThe asset key to load after laterite.css, or None.

add_asset(key, asset) serves a compiled-in file at {admin}/assets/{key}, content-named and cached for a year.

ConstructorMedia type
AdminAsset::css(bytes)text/css
AdminAsset::js(bytes)text/javascript
AdminAsset::new(mime, bytes)as given

Set the tokens

The document element carries data-lat-skin="<code>" on every admin page, the sign-in page and the setup page. A skin’s rules key on it.

:root[data-lat-skin="acme.dense"] {
  --topnav-h: 54px;
  --sidebar-w: 230px;
  --side-panel-w: 300px;
  --page-gutter: 20px;
  --card-pad: 14px;
  --control-h: 34px;
  --control-h-sm: 28px;
  --control-h-lg: 40px;
  --radius-control: 6px;
  --radius-card: 6px;
}
TokenSets
--topnav-hTop bar height
--sidebar-wThe sidebar’s width, the same open or closed; a longer title ends in an ellipsis, a description after two lines
--side-panel-wContext side panel width
--page-gutterPage padding
--card-padCard padding
--control-h, --control-h-sm, --control-h-lgInput and button heights
--radius-control, --radius-cardCorner radii

The brand’s accent and custom stylesheet load after the skin.

An unknown backend.skin code, a skin naming an unregistered stylesheet key, a duplicate skin code, or an asset key already served all abort the start.

Dashboard Widgets

A dashboard widget is a card a module registers for the home dashboard, a board each operator arranges for themselves.

Write a widget

use laterite_admin::widget::{Size, Widget, WidgetCx, WidgetReg};
use laterite_admin::{html::Markup, AdminRegistry};
use laterite_core::arrange::{slot, Position};
use laterite_core::{t, Text};
use std::sync::Arc;

struct Sales;

#[laterite_core::strata::async_trait]
impl Widget for Sales {
    fn code(&self) -> &str {
        "acme.sales"
    }
    fn label(&self) -> Text {
        t!("Sales today")
    }
    fn description(&self) -> Option<Text> {
        Some(t!("Orders and revenue since midnight."))
    }
    fn permission(&self) -> Option<&str> {
        Some("acme.view_sales")
    }
    fn size(&self) -> Size {
        Size::Third
    }
    fn refresh(&self) -> Option<u32> {
        Some(30)
    }
    async fn render(&self, cx: &WidgetCx<'_>) -> Result<Markup, String> {
        let count = acme::orders::today(cx.db()).await.map_err(|e| e.to_string())?;
        Ok(Markup::raw_unchecked(format!("<p class=\"lat-widget__name\">{count}</p>")))
    }
}

fn register(&self, registry: &mut laterite_core::Registry) {
    registry.add_widget(
        WidgetReg::new(Arc::new(Sales)).position(Position::new().slot(slot::APPLICATION)),
    );
}
MethodReturnsDefault
codevendor.name, unique across modulesrequired
labelthe heading, a Textrequired
descriptiona line under the label in Add widgetnone
permissionthe permission an operator needs to see itshown to every operator
sizeSize::Third, Size::Half, Size::Full: 7, 10 or 20 of the board’s columns when first placedHalf
refreshseconds between fetches of the bodyrendered once with the page
renderthe body as Markup; an Err shows a notice inside the framerequired

WidgetCx gives db(), base(), t(&Text), shell, user and size.

Arrange the dashboard

[backend.order]
"backend.dashboard" = ["acme.sales", "backend.welcome"]

Widgets sit in the backend.dashboard hierarchy; a widget may take slot::HOME, slot::APPLICATION or slot::SYSTEM, and lands in slot::APPLICATION unless its position says otherwise.

Replace a built-in widget

CodeShowsPermission
backend.welcomethe operator’s namenone
backend.managea card per section they may opennone
backend.activitythe latest audit-log entries, refreshed every minutebackend.view_audit_log
backend.statusthe framework version, database and timezonebackend.manage_plugins

A module registering a widget under a built-in’s code replaces it.

Boards

A board is a dashboard a screen hosts: widgets on a twenty-column grid, each fetched after the page opens, arranged by the people who may.

Host a board

use laterite_admin::board::{Board, BoardCx, Layout, Placement};
use laterite_admin::routes::{RouteCtx, Screen};
use laterite_admin::{AuthenticatedUser, PageHead, Shell};

struct Sales;

impl Screen for Sales {
    fn mount(&self, ctx: &RouteCtx) -> Router {
        let board = Arc::new(
            Board::new(
                "acme.sales",
                Layout::rows(vec![
                    vec![Placement::new("orders", "acme.orders_today", 7).locked()],
                    vec![Placement::new("trend", "acme.revenue", 20)
                        .properties(json!({ "days": "30" }))],
                ]),
            )
            .edit_permission("acme.view_sales")
            .share_permission("acme.manage_sales")
            .offer(["acme.*"]),
        );
        let (page, ctx, base) = (board.clone(), ctx.clone(), ctx.base_path().to_string());
        Router::new()
            .route("/", get(move |Extension(shell): Extension<Shell>,
                                  Extension(user): Extension<AuthenticatedUser>,
                                  Query(query): Query<HashMap<String, String>>| {
                let (board, ctx, base) = (page.clone(), ctx.clone(), base.clone());
                async move {
                    let cx = BoardCx { ctx: &ctx, shell: &shell, user: &user, query: &query, width: 20 };
                    let body = board.body(&cx, &base).await;
                    shell.page_with(PageHead::new(t!("Sales")).assets(&board.assets(&ctx)), body)
                }
            }))
            .merge(board.routes(ctx))
    }
}
Board methodSetsDefault
new(key, layout)the key its layouts are kept under, and the widgets it starts withrequired
editing(Editing)Off, Personal, Shared or BothBoth
view_permission(p)who may open it; its routes refuse anyone elsewhoever reaches the screen
edit_permission(p)who arranges their ownwhoever sees the board
share_permission(p)who changes the layout everyone seesnobody
allow(Allow)which of moving, resizing, adding, removing and configuring edit mode offersall
offer(codes)the kinds Add widget lists; acme.* is every kind under a prefixevery registered kind
with_kind(kind)a kind this board alone offersnone
rows()each row on its own linea widget sits under the one above it in its columns
carry(names)query parameters the board’s requests keep, such as rangenone
Placement methodSets
new(id, kind, width)the widget’s id on this board, its kind’s code, its columns of 20
properties(json)its settings
locked()not moved, resized or removed
keep()no Remove
fixed_settings()no Configure

Write a kind of widget

use laterite_admin::board::{BoardCx, Kind, KindReg};
use laterite_admin::form::FormField;

struct Revenue;

#[laterite_core::strata::async_trait]
impl Kind for Revenue {
    fn code(&self) -> &str {
        "acme.revenue"
    }
    fn label(&self) -> Text {
        t!("Revenue")
    }
    fn group(&self) -> Text {
        t!("Sales")
    }
    fn default_width(&self) -> u8 {
        10
    }
    fn properties(&self) -> Vec<FormField> {
        vec![FormField::of("days", t!("Days"), "select")
            .options(json!({ "options": [{ "value": "7", "label": "7" }, { "value": "30", "label": "30" }] }))]
    }
    fn title(&self, shell: &Shell, properties: &Value) -> Option<String> {
        Some(shell.t("Revenue"))
    }
    async fn render(&self, cx: &BoardCx<'_>, properties: &Value) -> Result<Markup, String> {
        let days = properties["days"].as_str().unwrap_or("30");
        acme::revenue::chart(cx.ctx.db(), days).await.map_err(|e| e.to_string())
    }
}

fn register(&self, registry: &mut laterite_core::Registry) {
    registry.add(KindReg::new(Arc::new(Revenue)));
}
Kind methodReturnsDefault
codevendor.name, unique across modulesrequired
label, group, descriptionits entry in Add widgetgroup Widgets, no description
permissionthe permission needed to see or add itnone
default_width, min_width, max_widthcolumns of 207, 3, 20
resizablewhether its width changestrue
onceat most one on a boardfalse
baredrawn with no card around itfalse
propertiesits settings as form fields; with none it has no Configurenone
properties_for(cx, current)the fields for a widget whose settings are current, where one setting decides another’s choicesproperties()
reload_onthe settings whose change draws Configure again through properties_fornone
check(properties)Err with what to tell the person; nothing is savedOk
titlethe heading above itnone
refreshseconds between fetchesfetched once
renderthe content as Markup; an Err is shown in the widget’s placerequired

BoardCx gives ctx, shell, user, query (the page’s query string) and width.

Let a caller read a widget

use laterite_admin::board::ReadCx;
use laterite_core::serde_json::{json, Value};

fn reads(&self) -> bool {
    true
}

async fn data(&self, cx: &ReadCx<'_>, properties: &Value) -> Result<Value, String> {
    let from = cx.query.get("from").map(String::as_str);
    let points = acme::revenue::by_day(cx.ctx.db(), properties["currency"].as_str(), from).await?;
    Ok(json!({ "points": points }))
}
let board = Arc::new(board);
ctx.add_surface(board.surface("/acme/sales", t!("Sales")));
Kind methodReturnsDefault
readswhether data answersfalse
data(cx, properties)what the widget shows, as JSONErr

ReadCx gives ctx, user and query. Board::surface(path, label) is the board as a surface:

PartControlsActs
the boardeach name it carriesshow
each widget, by its placement idits properties, and what the board carries where it readsread where it reads

Charts

A chart draws series of values over a period on a screen: as lines, bars or stacked bars, with a period bar above and a legend that hides and shows series.

Draw a chart

use chrono::Utc;
use laterite_admin::axum::extract::Query;
use laterite_admin::axum::response::Response;
use laterite_admin::axum::Extension;
use laterite_admin::chart::{Chart, ChartQuery, Kind, Period, Series, CHART_ASSETS};
use laterite_admin::{html::Markup, PageHead, Shell};
use laterite_core::t;

async fn orders(
    Query(query): Query<ChartQuery>,
    Extension(shell): Extension<Shell>,
) -> Response {
    let period = Period::from_query(&query, Utc::now().date_naive());
    // (day, value) rows for period.from()..=period.to().
    let web = acme::orders::by_day("web", period.from(), period.to()).await;
    let shop = acme::orders::by_day("shop", period.from(), period.to()).await;

    let chart = Chart::new("orders", period.clone())
        .title(t!("Orders"))
        .kind(Kind::StackedBar)
        .series(Series::daily("web", t!("Website"), &period, web))
        .series(Series::daily("shop", t!("Shop"), &period, shop));

    let mut body = period.bar(&shell, &query).into_string();
    body.push_str(chart.render(&shell, &query).as_str());
    shell.page_with(
        PageHead::new(t!("Orders")).assets(CHART_ASSETS),
        Markup::raw_unchecked(body),
    )
}

Period

Period::from_query(&query, today) reads these query parameters.

ParameterValuesResult
range7d, 30d, 90dThe last 7, 30 or 90 days. 30d when absent.
rangemonth, last_monthThis calendar month to today; the whole of last month.
range12mThe last 12 calendar months, a point a month.
rangecustomfrom to to, both YYYY-MM-DD, at most 1830 days.
byday, week, monthThe interval. day up to 370 days.
MethodReturns
from(), to()The first and last day.
interval()Interval::Day up to 92 days, Week up to 370, else Month, unless by set it.
points()The first day of each point.
previous()The period of the same length ending the day before.
query()The period as query parameters, for a link.
bar(&shell, &query)The period bar: the presets and a from and to date.

Series

// Dated rows: summed into the period's points, a missing point is zero.
Series::daily("web", t!("Website"), &period, vec![(day, 12.0)]);
// One value a point, in order.
Series::new("web", t!("Website"), vec![12.0, 9.0, 14.0]);

Chart

MethodDefaultEffect
Chart::new(id, period)id names the chart on the page: letters, digits, -, _.
.kind(Kind)Kind::LineLine, Bar or StackedBar.
.format(Format)Format::NumberNumber, or Money("EUR".into()) for EUR 1,234.50.
.title(text)noneThe heading above the legend.
.series(series)Adds a series; its colour follows its place.
.render(&shell, &query)The chart, showing the series show_<id> names.

Figures

use laterite_admin::chart::{stats, Format, Stat};

let row = stats(&shell, &[
    Stat::new(t!("Orders"), Format::Number.text(1284.0)).note(t!("In this period")),
    Stat::new(t!("Revenue"), Format::Money("EUR".into()).text(9120.5)),
]);

Colours

A skin sets --chart-1 to --chart-6.

:root { --chart-1: #0b6e4f; --chart-2: #c8553d; }

Settings Models

A settings model is a struct an operator edits from the admin panel.

Define one

use laterite_admin::settings::SettingsModel;
use serde::{Deserialize, Serialize};

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct SiteSettings {
    #[serde(default)]
    pub title: String,
    #[serde(default)]
    pub tagline: String,
    #[serde(default)]
    pub maintenance_mode: bool,
}

impl SettingsModel for SiteSettings {
    const CODE: &'static str = "acme.site";
}

Derive Serialize, Deserialize and Default, and give every field #[serde(default)]. CODE is the model’s key: namespace it to your application and never change it.

Read and write

let settings: SiteSettings = laterite_admin::settings::load(&db).await?;

let settings = SiteSettings { title: "Acme".into(), ..Default::default() };
laterite_admin::settings::save(&db, &settings).await?;

load returns Default when nothing is saved. save upserts the whole struct. By code, untyped:

let value = laterite_admin::settings::get(&db, SiteSettings::CODE).await?;
laterite_admin::settings::set(&db, "acme.site", &value.unwrap_or_default()).await?;

Edit it in the admin

Write the screen as a file beside the crate and register it from your module’s register:

# admin/settings.yaml
code: acme.site
label: Site
description: Public site title, tagline, and a maintenance switch.
category: General
icon: sliders-horizontal
permission: acme.manage_site
order: 10
fields:
  title:            { label: Site title, rules: [required] }
  tagline:          {}
  maintenance_mode: { type: switch }
registry.add_settings(laterite_admin::settings!("admin/settings.yaml"));

code is the model’s CODE. fields takes the entries a form descriptor takes: see Form Descriptor. A label left out is the field name, humanized. The file is read at compile time; a file read at run time goes through laterite_admin::settings::from_yaml(text, name).

KeyDefaultMeaning
coderequiredThe model’s CODE.
labelrequiredThe menu label.
descriptionnoneUnder the label in the settings index. At most 72 characters.
hintnoneAbove the form.
categorythe band’s nameGroups items in the index, in order of first appearance.
icona generic glyphAn icon. An unknown name stops the boot.
permissionany operatorHides the item from operators without the grant.
order, slot0, applicationSort within the band; the band (laterite_core::arrange::slot).
per_operatorfalseA value kept per operator; see below.
confirm_leavetrueAsk before leaving with changes unsaved.

The same screen, built in Rust:

use laterite_admin::form::FormField;
use laterite_admin::settings::SettingsItem;

registry.add_settings(
    SettingsItem::new("acme.site", "Site", vec![
        FormField::text("title", "Site title"),
        FormField::text("tagline", "Tagline"),
        FormField::switch("maintenance_mode", "Maintenance mode"),
    ])
    .description("Public site title, tagline, and a maintenance switch.")
    .category("General")
    .order(10)
    .icon("sliders-horizontal")
    .permission("acme.manage_site"),
);

One screen lists every item by category; one form edits each.

BuilderDescription
new(code, label, fields)The model’s CODE, the menu label, and its fields.
description(text)Under the label in the settings index. At most 72 characters.
hint(text)Above the form.
category(text)Groups items in the index, in order of first appearance.
slot(n)The band (laterite_core::arrange::slot); application unless set.
order(n)Sort within the band.
icon(name)An icon. An unknown name stops the boot.
permission(code)Hides the item from operators without the grant.
link(path)Places an existing screen in the settings menu, with no form.
confirm_leave(false)Leaving the screen with changes unsaved does not ask.

Headings

use laterite_admin::settings::category;

SettingsItem::new("acme.webhook_log", "Webhook Log", Vec::new())
    .category(category::LOGS)
    .link("/acme/webhook-log");
ConstantHeadingHolds
category::WEBSITEWebsiteThemes, Maintenance Mode
category::USERSUsersAdministrators, Roles
category::MAILMailMail Configuration, Mail Templates, Mail Branding
category::LOGSLogsAudit Log, Access Log, Request Log, Mail Log
category::SYSTEMSystemAdmin Branding, Plugins, Jobs, Scheduled Tasks

Items naming the same heading share it, whatever their band. Labels are in title case.

Fields are ordinary FormFields: text, textarea, switch, select, date, taglist, repeater, and any registered type through FormField::of(name, label, "vendor.type"). A type that refuses its input refuses the save.

A type’s keys go through options; a dependency through its builder:

FormField::textarea("notice", "Notice").options(serde_json::json!({ "rows": 4, "grow": false }))
FormField::text("slug", "Slug").preset("title", PresetShape::Slug)
FormField::date("send_at", "Send date").trigger(Trigger::new("show", "is_delayed", "checked"))

Keep a value per operator

use laterite_admin::settings::{load_for, save_for, PreferencesModel, SettingsItem};

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Desk {
    #[serde(default)]
    pub greeting: String,
    #[serde(default)]
    pub compact: bool,
}

impl PreferencesModel for Desk {
    const CODE: &'static str = "acme.desk";
}

registry.add_settings(
    SettingsItem::new("acme.desk", "My desk", vec![
        FormField::text("greeting", "Greeting"),
        FormField::switch("compact", "Compact rows"),
    ])
    .description("How the desk greets you.")
    .per_operator(),
);

let desk: Desk = load_for(&db, user.user.id).await?;
save_for(&db, user.user.id, &Desk { compact: true, ..desk }).await?;
ItemDescription
PreferencesModelThe same shape as SettingsModel; CODE is the key, one value per operator.
.per_operator()Keeps the item once per operator and lists it on their Preferences page, under More, at /preferences/<code>. The permission still applies; the category is not used.
load_for, save_forOne operator’s model, or the default when they have none; a write for one operator.
get_for, set_forThe same, as raw JSON.
AuditA deployment setting’s save is audited; an operator’s own preference is not.
registry.add_settings(
    SettingsItem::new("acme.pages", "Pages", Vec::new())
        .description("Manage site pages.")
        .category("Content")
        .icon("folder")
        .link("/pages"),
);

The path is under the admin mount. Any request at or under it renders the settings sidebar with the item active. The built-in Users and Roles register this way.

Change a model later

ChangeMigration
Add a fieldNone. A missing key deserializes to the field’s default.
Remove a fieldNone. A stale key is ignored.
Rename a fieldRead the old key, write the new one. Never reuse a CODE for an incompatible model.

Parameters

A parameter is a JSON value a module writes for itself, under a namespace::group.item key.

Read and write one

use laterite_core::parameters;

parameters::set(ctx.db(), "acme.blog::sync.cursor", &cursor).await?;
let cursor: Option<Cursor> = parameters::get(ctx.db(), "acme.blog::sync.cursor").await?;
let removed = parameters::reset(ctx.db(), "acme.blog::sync.cursor").await?;
FunctionDescription
get::<T>(db, key)Ok(None) when unset.
get_value(db, key)The raw serde_json::Value.
set(db, key, &value)Replaces any value held.
reset(db, key)Removes it; true when one was set.
Key partHolds
namespaceThe owning module’s id: acme.blog.
groupA family of items: sync.
itemThe item; may contain dots.

A malformed key is CoreError::Validation.

Go through the cache

let parameters = ctx.parameters();
parameters.set("acme.blog::sync.cursor", &cursor).await?;
let page: u32 = parameters.get_or("acme.blog::sync.page", 1).await?;
parameters.forget("acme.blog::sync.cursor");
MethodDescription
get, get_or, set, resetAs the functions, through the cache.
forget(key)The next read goes to the database.
clear()Drops every entry.
with_ttl(duration)On Parameters::new(db); the default is five minutes.

Read a key the framework writes

KeyValue
laterite.backend::setup.completed_atRFC 3339, written when the first administrator is created. The constant is laterite_admin::SETUP_COMPLETED_AT.

Add it to a module list

use laterite_core::parameters::ParametersModule;

laterite_admin::builtin_modules() includes it; an application composing its own list adds ParametersModule.

Logs

The admin keeps three read-only logs under Settings → System: the audit log of administrative changes, the access log of sign-ins, and the request log of URLs it could not serve. Each is gated by its own permission and exportable.

Read the audit log

Every administrative change is recorded in an append-only log; handlers do not opt in. Gated by backend.view_audit_log; superusers hold it.

FieldValue
WhenThe time of the change.
OperatorThe username, kept on the entry after the account is removed. A system change records the process name.
ActionA dot-keyed name: backend.role.update, backend.plugin.disable.
TargetA type, id and name, when the action has one.
ChangeRecorded
A role created or editedYes
A user’s permissions changedYes
A password changedYes, as backend.user.password_change, never the password
An operator created from setup or lat admin createYes, as backend.user.create, credited to the process
A plugin enabled or disabledYes
A settings model savedYes, without the contents
A record created or edited through a resource formYes
An operator’s own preferencesNo

Read the access log

Every sign-in, failure, lockout, sign-out and self-service password change, with the address and client it came from. Gated by backend.view_access_log.

ColumnHolds
WhenThe time of the event.
UsernameThe username attempted, searchable.
EventOne of the events below; a filter narrows to one.
AddressThe IP address, searchable.
ClientThe user agent; hidden until turned on in the list setup.
EventRecorded when
login_successA sign-in succeeded.
login_failureA password was wrong, or the username unknown.
locked_outAn attempt was refused by the lockout.
logoutAn operator signed out.
password_changedAn operator changed their own password.

Rows older than access_log_retention_days (see Authentication) are purged hourly.

Read the request log

Every URL the admin could not serve is counted, once per method, path and status, with the first and last time it was seen. Gated by backend.view_request_log.

# descriptors/request-log.yaml, built in
entity: backend_request_log
path: /request-log
permission: backend.view_request_log
ColumnHolds
Last seen, First seenWhen the URL was last and first requested.
Method, PathThe request; the path is kept to 512 characters, without its query string.
Status404.
HitsHow many times.

Rows are selected and deleted like any list’s.

Write audit entries from your own resources

A Resource with a form is audited as backend.<entity>.create and backend.<entity>.update, attributed to the signed-in operator, through a model listener.

A screen of your own records an entry with the builder:

use laterite_auth::AuditEntry;
use laterite_core::Actor;

let actor = Actor::user(operator.id, &operator.username);
auth.record_audit(
    AuditEntry::new(&actor, "acme.posts.publish").target("post", &post_id, Some(&post.title)),
)
.await?;
BuilderDescription
AuditEntry::new(actor, action)Who, and a dot-keyed action under your module’s id.
.target(type, id, name)What the action touched; name may be None.

The audit write runs after the change commits. A failed audit write is logged; the operator’s action stands.

Developer Section

With app.debug on, a superuser sees a Developer section in the admin’s navigation: what the application registered, from the running process.

[app]
debug = true
ScreenShows
RoutesEvery URL the application answers, with method, kind, owner and permission: the list lat routes prints.
Field typesEvery registered field type, rendered once with its defaults.
Mail previewsEvery mail template and layout, each with its preview.
RegistriesWhat every module contributed, by registry: resources, screens, settings, permissions, field and column types, widgets, public routes.

The section is absent when app.debug is off, and a 403 to an operator who is not a superuser. See Application and Server for app.debug.

Form Descriptor

One YAML file describes one resource: the table, where it mounts, who may reach it, and its list and form. This page covers the resource keys and the form half; the list half is on List Descriptor.

# descriptors/posts.yaml
entity: posts
path: /posts
title: Posts
permission: acme.blog.manage_posts
list:
  creatable: true
  deletable: true
  order_by: created_at
  order_dir: desc
  columns:
    title:      { searchable: true }
    status:     { type: status_pill, width: 10% }
    created_at: { type: datetime, align: right }
form:
  title: Post
  fields:
    title:  { span: 2/3, rules: [required, { max_length: 120 }] }
    status: { span: 1/3, type: select, options: [{ value: draft, label: Draft }] }
    body:   { type: textarea, rows: 8 }

Register it

registry.add_resource(laterite_admin::resource!("descriptors/posts.yaml"));

The path is relative to your Cargo.toml. The file is read at compile time: a missing or malformed one fails the build.

KeyDescription
entityThe table both screens read and write. Required.
pathWhere the resource mounts, under your module’s namespace. Required.
titleThe navigation label, and the default title of both screens. Required.
permissionThe permission gating it. Required once a form is present.
id_fieldThe primary key column. Default id.
listThe list screen. Required.
formThe create and edit screen. Optional.
importtrue, or { permission: ... }, to let records be imported into the resource. Needs form. See Bulk Import. Optional.
relationsRelated records, keyed by name, each a section on the edit page. See Related Records. Needs form. Optional.
sourceKeeps the records as files in a folder of the project. See Records in Files. Needs form. Optional.

entity, path and id_field reach both screens.

Name a field

Fields are a map. The key is the name, and they render in the order written:

fields:
  title: {}
  published_at: { type: date }

A missing label is made from the key: published_at becomes “Published at”. It is still translatable, and lat i18n extract finds it.

Set a field’s keys

An entry carries its own keys and its type’s, side by side:

fields:
  body:   { type: textarea, rows: 8, placeholder: Write here, span: 1/2 }
  price:  { input: number, min: 0, step: 0.01, help: In the shop's currency }
  status: { type: select, options: [{ value: draft, label: Draft }], hidden: true }
KeyDefaultDescription
labelfrom the keyThe label shown.
typetextThe field type. Every type and its keys: Form Fields.
rulesnoneValidation rules run on submit. See Validation.
helpnoneA line beneath the control.
span, breakfull, falseThe field’s place on the row. See below.
enterthe form’ssubmit, off, next.
preset, triggernoneFollows or watches another field. See Field Dependencies.
formatnoneThe shapes accepted, the one stored, and how a link column shows it. See Field Formats.
hiddenfalseSubmitted but never shown: a plain hidden input carrying its value.
transientfalseShown and submitted with no column behind it: not loaded, not written by the built-in writer; the form’s persist handler reads it (a password field).
translatablefalseMarks the value as translatable content, for a translation plugin to manage.
contextevery pageThe pages the field is on: create, update, preview, one or a list. See below.
defaultnoneWhat a new record’s form opens with: text, a number, true or false, or a list for a field holding several.
default_fromnoneAnother field whose default this one opens with.
help_abovenoneText above the control, under the label.
css_classnoneClasses added to the field’s wrapper.
container_attributesnoneAttributes added to the field’s wrapper, as a map. An event handler, class, style, id and data-lat-* are refused.
read_onlyfalseShown with its value, not editable. A save keeps what is stored; a new record takes the field’s default.
disabledfalseShown, not editable, and left out of every save.
permissionnoneA permission the user must hold to see the field or write it. An editable list cell of the field follows the same rule.
depends_onnoneA field, or a list of fields: when one changes, this field is drawn again. See Field Dependencies.

A key the type does not read is refused, naming the entry and the keys it accepts.

Put fields on tabs

form:
  fields:
    title: {}
  tabs:
    default_tab: Details
    active_tab: Pricing
    icons: { Details: file-text, Pricing: tag }
    fields:
      body:  { type: textarea }
      price: { tab: Pricing, input: number }
      stock: { tab: Pricing, input: number }
  secondary_tabs:
    fields:
      notes: { tab: Notes, type: textarea }
PartHolds
fieldsThe fields above the tabs. One naming a tab joins the tabs.
tabs.fieldsThe fields on the tabs, each on the tab it names.
secondary_tabs.fieldsA second set of tabs, under the first.
Key of tabs and secondary_tabsDefaultDescription
default_tabMiscThe tab for a field in the set that names none.
active_tabthe firstThe tab open on load: its label, or its place from 1.
iconsnoneAn icon for a tab, by the tab’s label.
linkabletrueA tab opens by the address’s fragment, and writes it.
stretchfalseThe panes fill the height left on the page.
css_classnoneA class on the set.
pane_css_classnoneA class on every pane, or a map of tab label to class.
identifiersfrom the labelAn HTML id for a tab, by its label.

Tabs show in the order their fields first name them. A refused save opens the first tab holding a refused field.

lat.get(document.querySelector('[data-lat-widget="formtabs"]')).open('tab-pricing');
lat.on('formtabs:opened', function (detail) { console.log(detail.tab); });
FormField::text("price", t!("Price")).tab(t!("Pricing"));

Keep a field to some pages

fields:
  code:  {}
  token: { context: create }
  notes: { type: textarea, context: [update, preview] }
  status@create: { type: select, options: [{ value: draft, label: Draft }] }
  status@update: { type: select, options: [{ value: draft, label: Draft }, { value: live, label: Live }] }
FormMeaning
context: updateOn that page alone.
context: [create, update]On each page listed.
name@updateThe same, written on the key. One column may have an entry a page.
PageRoute
create{path}/new
update{path}/{id}/edit
preview{path}/{id}/preview

A field off a page is not shown, checked or saved there. An import and an ability write through every field.

FormField::text("token", t!("Token")).context([FormContext::Create]);

Set the form’s keys

form:
  enter: off
  confirm_leave: false
  focus: off
  timestamps: true
  footprints: true
  slugs: { slug: title }
  encrypt: [api_key]
  actions:
    - { label: Reset to default, action: "acme/templates/{id}/reset", confirm: Reset this template? }
    - { label: Download PDF, action: "acme/templates/{id}/pdf", method: get }
  fields:
    title: { rules: [{ max_length: 80 }], counter: true }
    body:  { type: textarea, rows: 8, grow: false }
    token: { type: password, reveal: false }
KeyOnValuesDefault
titleThe formtextThe resource’s title
enterThe formsubmit, offsubmit: Enter submits; Cmd/Ctrl+Enter submits from a textarea as well
confirm_leaveThe formtrue, falsetrue: leaving with changes unsaved asks first
focusThe formauto, offauto: a new record opens with the cursor in its first field, a refused save in the first field it refused
timestampsThe formtrue, falsefalse; true stamps created_at and updated_at on write
footprintsThe formtrue, falsefalse; true stamps created_user_id and updated_user_id. See Model listeners
slugsThe forma map of slug column to a source column or a listNone. See Model listeners
encryptThe forma list of columnsNone. See Model listeners
relatedThe forma map of one-to-one recordsNone. See Related Records
relatedA fielda name under the form’s relatedNone: the field is stored on that record
persistThe forma persister nameThe built-in insert and update. See Persisters
actionsThe forma list of label, action (a path under the admin root, {id} for the record), method (post or get), confirm, permission (hides the button without the grant)None. Shown beside Save on an existing record; post submits the form to action, get links to it
after_saveThe formcreate, update, close (paths under the admin root, {id} for the record), created, updated (text)Save returns to the list and says “Saved.”. create and update send Save elsewhere, and that page then offers “Save and close”, which goes to close or the list
panelsThe forma list of src, title, permission, as a preview’s panelsNone. Drawn under an existing record’s form, each fetched from src once the page is open
linked_recordThe formmorph (the name n of the columns n_type and n_id), label, emptyNone. Links the owning record above an edit form, named by its resource’s title and its list’s first column; empty (“Not linked”) shows when the columns are empty
enterA fieldsubmit, off, nextThe form’s

A max_length rule also sets the control’s maxlength.

Preview a record

# descriptors/orders.yaml
preview:
  title: Order
  assets: [chart.css]
  panels:
    - { title: Payments, src: "acme/orders/{id}/payments", permission: acme.payments }
list:
  row_click: preview

preview: true takes every default.

preview:
  fields:
    code:   { label: Reference }
    total:  { input: number }
  relations: false
KeyDefaultDescription
titlethe form’sThe page’s title.
assetsnoneAsset keys the panels need on the page.
panelsnoneParts drawn under the values, in order.
fieldsthe form’s on previewThe preview’s own fields, written as the form’s are.
relationstrueThe record’s related lists show under the values, to read.
Panel keyDescription
srcA path under the admin root answering an HTML fragment, {id} for the record’s id. Fetched once the page is open.
titleThe heading over the panel.
permissionA user without it does not get the panel.
RouteShows
{path}/{id}/previewThe form’s fields with their values, none editable, an Edit button, then the panels.

A previewed resource’s list shows a Preview link on each row, before Edit.

Lay out the fields

Fields lay out on a twelve-column row and wrap as it fills.

fields:
  title:  { span: 2/3 }
  status: { span: 1/3 }
  body:   { break: true }
KeyDescription
spanThe share of the row: full (default), 1/2, 1/3, 2/3, 1/4, 3/4, or 1 to 12 columns. left, right, auto and half are halves; third and quarter as named.
breaktrue starts a new row.

Under 1100px a quarter becomes a half; under 768px every field takes the row.

Catch a bad key

A key the framework does not know is refused with its line:

error: line 11 column 19: unknown field `searchabel`, expected one of
label, type, sortable, invisible, width, align, permission, searchable

Write only the keys you set; everything else takes its default.

lat doctor parses every descriptors/**/*.yaml in the application and its plugins and names a typo without a build.

Read a descriptor at run time

resource! embeds a file. For YAML you loaded yourself, call the function behind it:

let resource = laterite_admin::descriptor::from_yaml(&yaml, "posts.yaml")?;

Field Dependencies

A field follows another as it is typed, or changes when another field’s state meets a condition.

fields:
  title: {}
  slug:  { preset: title }
  path:  { preset: { field: title, type: url } }
  is_delayed: { type: switch, label: Send later }
  send_at:
    type: date
    trigger: { action: show, field: is_delayed, condition: checked }
  format: { type: select, options: [{ value: csv }, { value: xml }] }
  delimiter:
    trigger: { action: show|empty, field: format, condition: "value[csv]" }
  topics: { type: checklist, options: [{ value: news }, { value: sport }] }
  region:
    trigger: { action: enable, field: "topics[]", condition: "value[sport]" }

Follow another field

KeyValue
presetThe field followed, or { field, type }. Follows it as it is typed, until this field is edited; emptying this field hands it back.
preset.typeslug (default): hello-world. url: /hello-world. file: spaces to hyphens. exact: as typed.

React to another field

KeyValue
trigger.actionshow, hide, enable, disable, empty, fill[value], several joined by |. A hidden field is left out of the submission.
trigger.fieldThe field watched. name[] watches every ticked value of a checklist.
trigger.conditionchecked, unchecked, value[x], value[x][y] (either), value[] (empty), value[*] (anything), value[csv*] (a prefix).

A field that follows or watches one the form does not have stops the boot, naming it. An action or condition the page does not know is refused when the file is read.

Options from a source

fields:
  country:  { type: select, options: acme.countries }
  state:    { type: select, options: acme.states, depends_on: country }
  timezone: { type: select, options: laterite.timezones }
use laterite_admin::options::{OptionCx, OptionEntry, OptionError, OptionSource, OptionSourceReg};

struct States;

#[async_trait]
impl OptionSource for States {
    async fn options(&self, db: &Db, cx: &OptionCx<'_>) -> Result<Vec<OptionEntry>, OptionError> {
        let country = cx.values.get("country").map(String::as_str).unwrap_or("");
        Ok(states_of(db, country)
            .await?
            .into_iter()
            .map(|s| OptionEntry::new(s.code, s.name))
            .collect())
    }
}

registry.add_option_source(OptionSourceReg::new("acme.states", Arc::new(States)));
registry.add_option_source(OptionSourceReg::fixed(
    "acme.sizes",
    vec![OptionEntry::new("s", "Small"), OptionEntry::new("l", "Large").note("From 40 cm")],
));
KeyValue
optionsOn a select, radio or checklist: the name of a registered source, in place of a list.
depends_onA field, or a list of fields. When one changes, this field is drawn again and its source is asked with the form’s current values.
OptionCxHolds
fieldThe field’s name.
valueThe field’s current value.
valuesEvery value the form holds, by field name. For a list filter: every filter value, by filter name.
idThe record being edited, on an edit page.
i18nThe request’s translator.
OptionEntryEffect
::new(value, label)A choice storing value, shown as label.
.note(text)A second line under the label (radio, checklist).
.disabled()Shown and not selectable (select, radio).
.group(heading)Sits under heading (select, checklist).
Built-in sourceOffers
laterite.timezonesEvery timezone name.
laterite.localesThe languages the admin is translated into.

A source name nobody registered, a field depending on one the form does not have, and a field depending on itself stop the boot. A row of a repeater lists its options in place.

Field Formats

A format says what a value looks like. The form accepts the shapes people type and stores one; a link column on the same field shows it short and linked.

form:
  fields:
    instagram_url:
      label: Instagram
      format: { base: "https://www.instagram.com/", prefix: "@", pattern: "[A-Za-z0-9._]{1,30}", lowercase: true }
list:
  columns:
    instagram_url: { type: link, new_tab: true }
FormField::text("instagram_url", t!("Instagram")).format(
    FieldFormat::new("https://www.instagram.com/").prefix("@").pattern("[A-Za-z0-9._]{1,30}").lowercase(),
)
KeyDefaultDescription
baserequiredThe address every value sits under, ending in /. A path is allowed: https://www.linkedin.com/in/.
prefixnoneShown before the name, and accepted before it when typed.
patternanyA regular expression the whole name must match.
lowercasefalseStores the name lowercased.
name_onlyfalseStores the name alone, acme, in place of the address.

What the form accepts

TypedStored
https://www.instagram.com/acme/?igsh=1https://www.instagram.com/acme
instagram.com/acmehttps://www.instagram.com/acme
@acmehttps://www.instagram.com/acme
acmehttps://www.instagram.com/acme
EmptyEmpty; add required to refuse it
Another site, a path or a name pattern refusesRefused on the field

What the list shows

StoredShown
https://www.instagram.com/acme@acme, linked
A value saved before the formatAs stored

A link column reads its field’s format; format on the column itself overrides it, for a list with no form.

list:
  columns:
    profile: { type: link, format: { base: "https://www.tiktok.com/", prefix: "@" } }

Related Records

A resource lists another entity’s records that belong to each of its own, as a section on the edit page. A has-many section has New, Edit and Delete; a many-to-many section has Attach, Edit and Remove.

Declare a has-many relation

# descriptors/products.yaml
relations:
  variants:
    label: Variant
    entity: product_variants
    foreign_key: product_id
    list:
      columns:
        sku: {}
        price: { type: money }
    form:
      fields:
        sku: { rules: [required] }
        price: { type: money }
Resource::new("/products", "Products", list)
    .form(form)
    .permission("acme.manage_products")
    .relation(RelationConfig::has_many("variants", "Variant", "product_variants", "product_id", variants_list, variants_form))

Declare a many-to-many relation

# descriptors/products.yaml
relations:
  tags:
    label: Tag
    entity: tags
    pivot:
      table: product_tags
      parent_key: product_id
      related_key: tag_id
      source: acme.tags
    list:
      columns:
        name: {}
    form:
      fields:
        note: {}
Resource::new("/products", "Products", list)
    .form(form)
    .permission("acme.manage_products")
    .relation(
        RelationConfig::belongs_to_many(
            "tags",
            "Tag",
            "tags",
            PivotConfig::new("product_tags", "product_id", "tag_id", "acme.tags"),
            tags_list,
        )
        .form(note_form),
    )
// The picker source Attach searches, registered with the admin.
Contributions {
    picker_sources: vec![PickerSourceReg::new(
        "acme.tags",
        Arc::new(TableSource::new("tags", "id", "name")),
    )],
    ..Default::default()
}

Declare a polymorphic relation

# descriptors/notes.yaml, and the same in descriptors/tasks.yaml
relations:
  comments:
    label: Comment
    entity: comments
    morph: commentable
    list:
      columns:
        body: {}
    form:
      fields:
        body: { rules: [required] }
  tags:
    label: Tag
    entity: tags
    pivot:
      table: taggables
      parent_key: taggable_id
      parent_type: taggable_type
      related_key: tag_id
      source: acme.tags
    list:
      columns:
        name: {}
RelationConfig::has_many("comments", t!("Comment"), "comments", "", list, form).morph("commentable");
PivotConfig::new("taggables", "taggable_id", "tag_id", "acme.tags").parent_type("taggable_type");
ColumnHolds
commentable_idThe parent’s id
commentable_typeThe parent’s entity, such as notes
taggable_typeOn the pivot: the parent’s entity

The type columns are written from the URL and kept hidden in the form. A section lists only rows whose type is its parent’s entity.

Edit a one-to-one record in the form

# descriptors/authors.yaml
form:
  related:
    profile: { entity: profiles, foreign_key: author_id }
    address: { entity: addresses, belongs_to: address_id }
  fields:
    name: { rules: [required] }
    bio:  { related: profile }
    city: { related: address }
form.related.insert("profile".into(), RelatedRecord::has_one("profiles", "author_id"));
form.related.insert("address".into(), RelatedRecord::belongs_to("addresses", "address_id"));
related keyHolds
entityThe related table
foreign_keyHas-one: the related table’s column holding this record’s id
belongs_toBelongs-to: this table’s column holding the related record’s id
id_fieldThe related table’s id column; default id
timestampstrue: the related row’s created_at and updated_at are stamped as it is written
optionalBelongs-to, true: with every field of it empty no record is made, and one already there is let go (this record’s column is cleared, the related row stays)
Step of a saveWrites
1Each belongs-to record, inserted or updated; its id goes into this record’s column
2This record
3Each has-one record, inserted or updated with this record’s id
4The media links of this record’s media fields

All four run in one transaction: a failure in any of them saves none. A field with related cannot carry unique.

# descriptors/notes.yaml
soft_delete: true
relations:
  comments:
    title: Comments
    entity: comments
    morph: commentable
    soft_delete: true
    delete: true
    section: false
RelationConfig::has_many("comments", t!("Comment"), "comments", "note_id", list, form)
    .delete()
    .section(false)
Parentsoft_deletedelete
Moved to the trashRows go to the trash with it
RestoredRows that went with it come back
Deleted, or deleted permanently from the trashRows are deleted in the same transaction

A deleted row’s own delete relations, declared on a resource over its entity, go with it:

# descriptors/comments.yaml
entity: comments
relations:
  reactions:
    title: Reactions
    entity: reactions
    foreign_key: comment_id
    delete: true
    section: false

Delete asks first and names each relation by its title: “These are deleted with them: Comments, Reactions.” The rows’ own listeners do not run.

Set the keys

KeyDefaultDoes
labelrequiredOne related record, singular: the New or Attach button, the child form’s title.
titlethe name, humanizedThe section heading.
entityrequiredThe related table.
foreign_keyone of threeHas-many: the column on the related table holding the parent’s id. Written by the framework from the URL; a field of that name in form is kept hidden.
morphone of threePolymorphic has-many: name for the name_id and name_type columns.
soft_deletefalseHas-many: rows go to the trash with the parent and come back with it. See Soft Delete.
deletefalseHas-many: rows are deleted with the parent. See Delete related rows with their parent.
sectiontruefalse gives the relation no section and no pages; soft_delete and delete still apply, and list and form are not needed.
pivotone of threeMany-to-many: the table joining the two, keys below.
listrequiredThe section’s list: the same keys as a resource’s list. Its columns are the related table’s.
formrequired for has-manyHas-many: the related record’s form. Many-to-many: the fields kept on the pivot row, asked for on Attach; empty gives the section no Edit.
permissionthe parent’sA permission the user must also hold.
Pivot keyDefaultDoes
tablerequiredThe pivot table.
parent_keyrequiredThe column holding the parent’s id. Written by the framework from the URL.
related_keyrequiredThe column holding the related record’s id. Chosen in the picker on Attach, fixed afterwards.
sourcerequiredThe registered picker source Attach searches.
id_fieldidThe pivot row’s id column.
parent_typenonePolymorphic: the pivot column holding the parent’s entity.

Reach the section

PathDoes
/products/7/editThe parent’s form, then a section per relation.
/products/7/variantsThe section’s list on its own, sorted and paged.
/products/7/variants/newHas-many: a new related record. Many-to-many: Attach, a record from the picker with the pivot fields. Saves return to the parent.
/products/7/variants/3/editHas-many: the related record 3. Many-to-many: pivot row 3’s fields. Only under its own parent.
/products/7/variants/deleteHas-many: deletes the selected records through the related entity’s listeners and persister. Many-to-many: deletes the selected pivot rows the same way; the records stay.
/products/7/variants/reorderHas-many with reorder on its list: moves one record within the parent’s section. See Trees and Reordering.

A relation needs a form on the parent. A relation’s name is a path segment and cannot be new, edit, delete, import, export or columns. Attaching a record already attached, or one the related table does not hold, is refused with a message.

Validation

A form field carries rules. A failed submission re-renders the form with a message under each field and writes nothing.

Declare rules

use laterite_admin::form::FormField;

let fields = vec![
    FormField::text("email", "Email").required().email().unique(),
    FormField::text("name", "Name").required().max_length(120),
];
fields:
  email: { rules: [required, email, unique] }
  name: { rules: [required, { max_length: 120 }] }
BuilderRule
.required()Non-empty in every mode.
.required_on(Mode::Create)Non-empty on create, or on update, only.
.min_length(n) / .max_length(n)Length bounds. min is skipped when empty.
.email()A valid email address.
.unique()Not already used in the column. Ignores the edited row on update.

The generic create and edit handlers validate before writing.

Call the engine

use laterite_core::validation::{validate, FieldRules, Mode, Rule};

let rules = vec![FieldRules::new("email", "Email", vec![Rule::Required, Rule::Email])];
let bag = validate(&db, "users", "id", &rules, &data, Mode::Create, None).await?;
if bag.is_empty() {
    // persist
}

validate_fields runs the rules without the database; validate adds the unique probe. The result is an ErrorBag; empty means valid.

Register a rule

use laterite_core::validation::{RuleCx, ValidationRule, ValidationRuleReg};
use laterite_core::Text;

struct DiffersFrom;

#[laterite_core::strata::async_trait]
impl ValidationRule for DiffersFrom {
    async fn check(&self, cx: &RuleCx<'_>, value: &str) -> Result<(), Text> {
        let other = cx.args.first().and_then(|name| cx.data.get(name));
        if other.is_some_and(|o| o.trim() == value) {
            return Err(Text::new("{label} must differ.").arg("label", Text::dynamic(cx.label)));
        }
        Ok(())
    }
}

// In a module's `register`:
registry.add(ValidationRuleReg::new("acme.differs_from", Arc::new(DiffersFrom)));
fields:
  code: { rules: [required, acme.uppercase, { acme.differs_from: name }] }
RuleCx fieldHolds
field, labelThe field being checked and its label
argsThe descriptor’s arguments as text: { acme.between: [1, 10] } gives ["1", "10"]
dataEvery submitted value, by field name
modeMode::Create or Mode::Update
db, table, edited_idThe database, the form’s table, the record being updated

A rule runs after the built-in rules pass for that field, and skips an empty value unless implicit() returns true. A registered name is dotted (vendor.rule). A field naming a rule no module registered fails boot.

Read what a submission answers

OutcomeResponse
Refused422, the form re-rendered with its values. An htmx submit swaps the form; a plain one gets the whole page.
SavedA flash, then the list: HX-Redirect for htmx, 303 otherwise.
API422 with { "field": ["message", ...] }.

Writing a Field Type

A field type renders one kind of control on any form or settings page that names it, and turns what it submits into the value that reaches the database.

Implement the type

impl FieldType for SwitchField {
    fn view_key(&self) -> &'static str {
        "switch"
    }

    fn view_model(&self, cx: &FieldCx<'_>) -> FieldVm {
        scalar_vm("switch", cx)
    }

    fn render_default(&self, vm: &FieldVm) -> Markup {
        Markup::from_template(&SwitchTmpl { vm }).unwrap_or_default()
    }

    fn to_attr(
        &self,
        field: &SubmittedField<'_>,
        _opts: &ResolvedOptions,
        _mode: Mode,
    ) -> Result<Option<AttrValue>, String> {
        Ok(Some(AttrValue::Bool(stored_is_on(field.value()))))
    }
}
MethodRole
view_keyThe name a descriptor uses. A dotted vendor.name; a taken key aborts the boot.
view_modelThe submitted or saved value as a view-model.
render_defaultThe markup.
to_attrThe submitted string as the typed value that reaches the database. Err refuses the save.
option_keysThe keys the type reads from a field’s entry. Any other key is refused by name.
submittedFor a type of several controls: what it submitted, gathered into one value. The rules read it, and a refused save is rebuilt from it.
resolve_optionsThose keys, typed once.

Built in: text, textarea, select, radio, checklist, taglist, switch, date, password, reference, repeater.

Register it

registry.add_field_type(FieldTypeReg::new(Arc::new(MoneyField)));

FormField::of("price", "Price", "acme.money")

One registration covers forms and settings. A descriptor naming an unregistered type aborts the boot.

Declare its keys

price: { type: acme.money, currency: EUR, precision: 2, span: 1/3 }
fn option_keys(&self, _raw: &serde_json::Value) -> Option<Vec<String>> {
    Some(vec!["currency".into(), "precision".into()])
}

A type’s keys are written on the field, beside the field’s own.

Meet the contract

RuleHow
Works with no configurationEvery key has a default chosen for the common case: type: acme.money alone renders a usable control.
Each default can be turned offOne key per behaviour, named for what it does, read from the field’s entry.
Its keys are declaredoption_keys lists them; a typo is refused by name.
Enter stays inside itA root marked data-lat-enter-scope when the control holds an input of its own. See JavaScript API.
It says what it didlat.emit(root, 'acme.money:changed', detail); a before- event is cancelable.
It can be drivenThe island’s initialiser returns its controller; lat.get(el) finds it.
It is listedOne row per behaviour in your plugin’s docs: the default, and the key that changes it. See Behaviours.
Works before scripts loadThe markup submits as a plain form; a script island improves it.

Editor Commands and Snippets

A module adds entries to the Insert menu of the rich and markdown editors: a command that inserts fixed content, or a snippet with properties the user fills. The editors show the Insert button once at least one command or snippet exists.

Add a command

use laterite_admin::editor::{EditorCommand, Insert, Surface};
use laterite_admin::AdminRegistry;

fn register(&self, registry: &mut laterite_core::Registry) {
    registry.add_editor_command(EditorCommand::new(
        Surface::Rich,
        "acme.callout",
        t!("Callout"),
        Insert::Html(r#"<blockquote><p>Note</p></blockquote>"#.into()),
    ));
    registry.add_editor_command(EditorCommand::new(
        Surface::Markdown,
        "acme.callout",
        t!("Callout"),
        Insert::Text("> **Note**\n> ".into()),
    ));
}
FieldValues
SurfaceRich (the richeditor field, inserts HTML), Markdown (the markdown field, inserts text)
keystable within the surface; a later registration with the same key replaces the earlier
labela Text, localized for the user
InsertHtml(..) for Rich, Text(..) for Markdown

Offer snippets

use laterite_admin::editor::{Snippet, SnippetProperty, SnippetPropertyKind, SnippetSource};

struct Embeds;

#[laterite_core::strata::async_trait]
impl SnippetSource for Embeds {
    async fn list(&self, _db: &laterite_core::Db) -> Vec<Snippet> {
        vec![Snippet {
            code: "acme.map".into(),
            name: "Map".into(),
            description: Some("A map centred on an address".into()),
            properties: vec![SnippetProperty {
                code: "address".into(),
                title: "Address".into(),
                kind: SnippetPropertyKind::String,
                default: None,
                options: Vec::new(),
            }],
        }]
    }
}

registry.add_snippet_source(std::sync::Arc::new(Embeds));
FieldValues
SnippetPropertyKindString, Dropdown (with options as (value, label) pairs), Checkbox
list(db)asked each time an editor opens its Insert menu; the list may change while the application runs

An inserted snippet is <figure data-snippet="<code>" data-properties="{...}"></figure>. A theme declares snippets on its partials and renders them with the content filter; a component is offered with ComponentReg::snippet and runs after the page renders; see Snippets. A module that lists snippets from a source renders them on its own pages the same way.

Read the menu

GET /admin/editor/menu?surface=richeditor
{ "commands": [{ "key": "acme.callout", "label": "Callout", "html": "..." }],
  "snippets": [{ "code": "acme.map", "name": "Map", "properties": [...] }] }

List Descriptor

The list half of a resource file: its columns, search, ordering, paging and the capabilities it offers. The resource keys around it are on Form Descriptor.

# descriptors/posts.yaml
entity: posts
path: /posts
title: Posts
permission: acme.blog.manage_posts
list:
  creatable: true
  deletable: true
  exportable: true
  order_by: created_at
  order_dir: desc
  per_page: 25
  per_page_options: [25, 50, 100]
  no_records_message: No posts yet.
  search: { prompt: Search posts }
  columns:
    title:      { searchable: true }
    status:     { type: status_pill, width: 10%, labels: [{ value: draft, label: Draft }] }
    created_at: { type: datetime, align: right }
  filters:
    status: { type: select, options: [{ value: draft, label: Draft }] }
  toolbar:
    - { label: Archive, href: /posts/archive, icon: archive, primary: false }

Set the list’s keys

KeyDefaultDescription
columnsThe columns, keyed by field name, in order. Required.
relatednoneOne-to-one records a column can be read from, by name.
titlethe resource’sThe screen title.
order_by, order_dirid, descThe first sort; asc or desc.
per_page25Rows a page.
per_page_optionsnonePage sizes offered in the list setup; empty offers no choice.
creatablefalseOffers New.
deletablefalseRows can be selected and deleted, and a record’s edit page offers Delete.
protectednoneA boolean column; a row it marks has no checkbox and no Delete.
exportablefalseOffers the export menu. See Export.
searchonThe search box; keys below.
filtersnoneFilters above the table, keyed by field name. See Filters.
no_records_message“No records yet.”Shown when the list has no records at all.
row_clickopenWhere a click on a row goes: open (the record’s edit page), preview (its preview), none, or an address pattern. See below.
remembertrueThe sort, search, filters and page a user last used come back when they return.
reorderofftrue orders rows by sort_order; { column: position } names the column. See Trees and Reordering.
treeofftrue nests rows on parent_id; { parent_key, source } names the column and a picker source for Move to. See Trees and Reordering.
toolbarnoneExtra buttons beside New; keys below.

import is a resource key beside list: see Bulk Import.

KeyDefaultDescription
search.enabledtruefalse removes the box.
search.prompt“Search”The placeholder.
search.on_enterfalseAsk on Enter only.
toolbar[].labelThe button’s text. Required.
toolbar[].hrefA path under the admin root, or an absolute URL. Required.
toolbar[].iconnoneAn icon name from the shared set.
toolbar[].permissionnoneHidden from a user who lacks it.
toolbar[].primarytrue renders it as the prominent action. Required.

Send a row click anywhere

list:
  row_click: "acme/orders/{id}/summary"
list:
  row_click: "https://track.acme.com/parcels/{tracking_code}?order={id}"
PatternGoes to
acme/orders/{id}/summaryA path under the admin root.
/shop/orders/{id}A path on the site.
https://...A full address.
PlaceholderFills in
{id}The record’s id.
{column}A column on the list, as stored, URL-encoded.

A row with an empty value for a placeholder opens nothing. A record in the trash opens nothing.

ListConfig::new("orders", t!("Orders"), columns)
    .row_click(RowClick::Url("acme/orders/{id}/summary".into()));

Name a column

Columns are a map. The key is the name, and they render in the order written:

columns:
  title: {}
  created_at: { type: datetime }

A missing label is made from the key: created_at becomes “Created at”. It is still translatable, and lat i18n extract finds it, as it finds the label of every entry under a column’s labels.

Set a column’s keys

KeyDefaultDescription
labelfrom the keyThe header.
typetextThe column type. Every type: List Columns.
sortabletrueThe header sorts. Empty values come last either way.
invisiblefalseHidden until the user picks it from the column chooser.
widthsharedA CSS width, 10% or 120px.
alignleft, center, right.
permissionnoneA user without it does not see the column; it is then not queried, sorted, searched, picked or exported for them.
searchabletext columnsWhether the search box looks in this column.
labelsnoneWhat a stored value reads as: [{ value: login_success, label: Signed in }]. A value not listed shows as stored.
editablefalseThe cell is the form field’s control, saved on change. The field must be on the resource’s form.
relatednoneThe record under the list’s related the column is read from.
# descriptors/authors.yaml
list:
  related:
    profile: { entity: profiles, foreign_key: author_id }
    address: { entity: addresses, belongs_to: address_id }
  columns:
    name: {}
    city: { related: address }
    bio: { related: profile, sortable: false }
ListConfig::new(
    "authors",
    t!("Authors"),
    vec![
        ListColumn::new("name", t!("Name")),
        ListColumn::new("city", t!("City")).related("address"),
    ],
)
.related("address", RelatedRecord::belongs_to("addresses", "address_id"));

The key is the related table’s column. The column sorts, searches and exports as the list’s own do. related takes the keys of a form’s related.

A key the framework does not know is refused with its line; lat doctor names it without a build.

Filters

A filter narrows the list to rows matching a value the user picks. Only a value a declared filter accepts reaches the query.

list:
  filters:
    status:     { type: select, options: [{ value: draft, label: Draft }, { value: live, label: Live }], default_value: live }
    featured:   { type: boolean }
    author:     { type: text }
    views:      { type: number }
    created_at: { type: date, permission: acme.blog.audit }
KeyDefaultDescription
labelfrom the keyThe control’s label.
typetextboolean, select, text, number or date.
optionsA select filter’s choices: a list of { value, label }, or the name of an option source. Required for select.
depends_onnoneOn a select with a source: the filters whose values the source reads. See select.
default_valuenoneApplied when the request names no value for this filter: the screen opens already narrowed. Clearing it is still “no filter”.
permissionnoneA user without it does not see the filter, and its default is not applied.

A key written bare (author:) is a text filter with every default.

list:
  related:
    author: { entity: authors, belongs_to: author_id }
  filters:
    views_min:   { label: Views at least, type: number, column: views, match: at_least }
    views_max:   { label: Views at most, type: number, column: views, match: at_most }
    author_city: { label: Author's city, type: text, column: city, related: author }
KeyDefaultDescription
columnthe filter’s keyThe column compared, so two filters narrow one column.
matchequalsOn a number filter: equals, at_least or at_most.
relatednoneA record under the list’s related; the filter compares its column.

Pick a scope type

TypeThe value reaches the query as
boolean1 or 0: rows where the column is true or false.
selectA declared value, matched exactly; any other value is dropped.
textA substring match, folded the way the search box folds.
numberA whole number, matched exactly.
dateA YYYY-MM-DD day; a date column and a stored timestamp both answer.

Each type, with its example, is on Filter Scopes.

Declare a filter from code

use laterite_admin::list::{FilterOption, ListFilter};

let status = ListFilter::select("status", "Status", vec![
    FilterOption::new("draft", "Draft"),
    FilterOption::new("live", "Live"),
]).default_value("live");
let created = ListFilter::date("created_at", "Created").require("acme.blog.audit");
ConstructorType
ListFilter::boolean(field, label)boolean
ListFilter::select(field, label, options)select
ListFilter::select_from(field, label, source)select, its choices from an option source; .depends_on([..]) names the filters it follows.
ListFilter::text(field, label)text
ListFilter::number(field, label)number
ListFilter::date(field, label)date
ListFilter::of(field, label, type)Any declared type, with no options.
MethodSets
.column(name)column
.at_least(), .at_most()match
.related(name)related
.default_value(value)default_value
.require(permission)permission

Carry a filter in a URL

/admin/posts?f_status=draft&f_featured=1&q=launch&sort=created_at&dir=desc
ParameterValue
f_<name>The filter’s value.
qThe search.
sort, dirThe sort column and asc or desc.

The export link carries the same parameters and downloads the list the screen shows.

Trees and Reordering

A list keeps its rows in an order of their own, shows them as a tree on a parent column, or both.

Reorder rows

list:
  reorder: true
list:
  reorder: { column: position }
ListConfig::new("pages", "Pages", columns).reorder("position")
KeyDefaultDoes
reorderofftrue keeps the order in sort_order; { column: position } names the column. An integer column, not null, default 0.
reorder.columnsort_orderThe column holding each row’s position.

The list opens in that order with a grip to drag and Move up / Move down on every row; a sorted, searched or filtered view shows neither. A has-many section’s list takes the same key; see Related Records.

Show rows as a tree

list:
  tree: true
list:
  tree: { parent_key: folder_id, source: acme.folders }
use laterite_admin::list::TreeConfig;

ListConfig::new("folders", "Folders", columns)
    .tree(TreeConfig::new("folder_id").move_to("acme.folders"))
KeyDefaultDoes
treeofftrue reads the parent from parent_id; { parent_key, source } names the column and a picker source.
tree.parent_keyparent_idThe column holding a row’s parent id, null at the top level.
tree.sourcenoneA registered picker source over this entity. With it, every row offers “Move to”, which picks the new parent from the source or leaves it empty for the top level. A record never moves under itself.

The list opens on the rows with no parent; a row with children expands in place, or opens them as a page with scripting off. With reorder too, a move stays among one parent’s children. A has-many section ignores tree.

Reach the routes

PathMethodDoes
/products/reorderPOSTMoves id with move=up or move=down, or before=<id> or after=<id>, and shows page again; parent names the branch under a tree.
/products/7/moveGET, POSTThe “Move to” form for record 7, and the move itself.

Both answer an htmx request with the list region and a plain one with the page.

Writing a Column Type

A column type renders one kind of cell on any list that names it.

Implement the type

use laterite_admin::html::Markup;
use laterite_admin::list::{CellCx, CellVm, ColumnType, ColumnTypeReg};

struct Rating;

impl ColumnType for Rating {
    fn view_key(&self) -> &'static str { "acme.rating" }
    fn view_model(&self, cx: &CellCx<'_>) -> CellVm { /* ... */ }
    fn render_default(&self, vm: &CellVm) -> Markup { /* ... */ }
}
MethodRole
view_keyThe name a column’s type uses. A dotted vendor.name.
view_modelThe cell’s value as a view-model.
render_defaultThe markup.
option_keysThe keys the type reads from its column entry; any other key is refused at boot.
checkChecks the column’s keys when the list is read; an error stops the boot.
CellCxGives
valueThe stored value, as text.
tz, localeThe display timezone and locale.
optionsThe column’s entry, for the type’s own keys.
option_str(key)One of those keys, as text.
field(column)Another value in the row; field("id") is the record’s id.
icon(name)Inline SVG for an icon from the set.
base()The admin mount, for an address inside the admin.
CellCx::new(value, tz, locale)A context for a test, with with_options, with_row, with_icons, with_base.

Register it

registry.add(ColumnTypeReg::new(Arc::new(Rating)));
columns:
  rating: { type: acme.rating }

A taken key aborts the boot; so does a column naming a key nobody registered.

Export

A resource opts into exporting its list as a file; the download carries the rows the screen shows, minus the paging.

# descriptors/posts.yaml
list:
  exportable: true
ListConfig::new("posts", "Posts", columns).exportable()
KeyDefaultDescription
exportablefalseMounts /export under the resource and shows the export menu beside New.

Choose the format

GET /admin/posts/export?format=csv&q=launch&sort=created_at&dir=desc&f_status=draft
FormatHeaded byContent type
csv (default)The column labels, localized.text/csv
jsonThe column names.application/json

The file carries the columns the user can see and has chosen, the search, the filters and the sort of the list it was offered from. An unknown format is CSV.

Keep within the limit

LimitValue
Rows20 000

Past it the export is refused with a message asking to narrow the list.

Gate it

WhoGets
A user holding the resource’s permissionThe export menu and the route.
A user without a column’s permissionA file without that column.
Anyone else403 Forbidden.

Form Fields

Every built-in form field type, with the keys it reads. The keys every field takes (label, span, rules, …) are on Form Descriptor; a type of your own is Writing a Field Type. A key a type does not read is refused, naming the entry and the keys it accepts.

text

fields:
  email: { type: text, input: email, placeholder: you@acme.test }
  price: { input: number, min: 0, step: 0.01 }
  site:  { input: url, copy: true }
KeyDefaultDescription
inputtexttext, email, tel, number, url, color.
placeholdernoneThe placeholder.
counterautoauto, true, false. auto: with a max_length rule, shown once four fifths of it are used.
min, max, stepnoneA number input’s bounds and step.
copyfalseA url input: a button copying the value.

text is the type when none is written. An email input adds the email rule.

textarea

fields:
  body: { type: textarea, rows: 8, placeholder: Write here, grow: false }
KeyDefaultDescription
rowsThe height, in lines.
placeholdernoneThe placeholder.
growtrueAs tall as its text, from rows up to most of the window.
counterautoAs for text.

richeditor

fields:
  body: { type: richeditor, rows: 12, toolbar: [format, bold, italic, "|", link, image] }
KeyDefaultDescription
rowsThe height, in lines.
placeholdernoneThe placeholder.
toolbarevery entry, in this orderA list from format, bold, italic, underline, strike, bullet_list, ordered_list, link, image, table, rule, undo, redo, `

Stores HTML kept to that set; an image from the library is linked to the record.

markdown

fields:
  body: { type: markdown, rows: 12, preview: side }
  terms: { type: markdown, preview: side, preview_url: acme/terms/preview }
KeyDefaultDescription
rowsThe height, in lines.
placeholdernoneThe placeholder.
previewtabtab (or true): a Preview tab. side: the preview beside the text, rendered again as the text or any other field of the form changes. off (or false): none.
preview_urlthe built-in rendererAn endpoint of your own, under the admin (acme/terms/preview) or absolute (/render). It receives the form’s fields by POST, with text holding the editor’s content, and answers HTML, or a PDF to show the document itself.

Stores the markdown as written; the site renders it with the markdown filter.

codeeditor

fields:
  styles: { type: codeeditor, language: css, rows: 20, wrap: true }
KeyDefaultDescription
languagetexttext, html, css, javascript, json, yaml, markdown, jinja.
rowsThe height, in lines.
line_numberstrueNumbers in the gutter.
wrapfalsefalse: long lines scroll.
placeholdernoneThe placeholder.

select

fields:
  status: { type: select, options: [{ value: "", label: Any }, { value: draft, label: Draft }], search: auto }
KeyDefaultDescription
optionsA list of { value, label, disabled, group }, or the name of an option source. group is the heading the choice sits under.
searchautoauto, true, false. auto: past 10 choices, the dropdown is searched. An option with an empty value is what clearing chooses.

radio

fields:
  size: { type: radio, options: [{ value: s, label: Small }, { value: l, label: Large }] }
KeyDefaultDescription
optionsA list of { value, label, note, disabled }, or the name of an option source. note is a second line under the label.

checklist

Boxes in groups. The column holds the ticked values as a JSON array of text.

fields:
  topics:
    type: checklist
    rules: [required]        # a box must be ticked
    options:
      - { value: news, label: News }
      - group: Sport
        options:
          - { value: football, label: Football, note: Every league }
          - { value: cricket, label: Cricket }
    select_all: auto
    search: auto
    expand: auto
KeyValuesDefault
optionsA list of { value, label, note } and { group, options }, nested to any depth, or the name of an option source.None
select_allauto, true, falseauto: past 10 choices
searchauto, true, falseauto: past 20 choices
expandauto, all, noneauto: past 10 choices in more than one group, a group with every box ticked or none starts closed and a group partly ticked starts open

A value listed twice stops the boot, naming it.

taglist

Short texts typed one at a time. The column holds them as a JSON array of text.

fields:
  aliases:
    type: taglist
    placeholder: "Another name"
    rules: [required]        # at least one tag
KeyValuesDefault
placeholdertextNone

Enter or a comma adds what is typed; a pasted list splits on commas and lines. A tag typed twice is kept once. In a repeater row:

fields:
  outlets:
    type: repeater
    fields:
      name:    {}
      domains: { type: taglist }
lat.on('taglist:changed', function (detail) { console.log(detail.tags); });

switch

fields:
  is_live: { type: switch, label: Published }

No keys. A yes or no over a boolean column.

section

fields:
  delivery:  { type: section, label: Delivery, help: Where and when the order ships. }
  address:   {}
  ship_date: { type: date }

No keys. A heading over the fields after it, with help as the line beneath. Nothing is stored or submitted. A trigger shows and hides the heading:

fields:
  kind:    { type: select, options: [{ value: post }, { value: event }] }
  when:    { type: section, label: When, trigger: { action: show, field: kind, condition: "value[event]" } }
  starts:  { type: date, trigger: { action: show, field: kind, condition: "value[event]" } }

date

fields:
  published_at: { type: date }

No keys. The value must be a date.

password

fields:
  token: { type: password, reveal: false }
KeyDefaultDescription
revealtrueA button shows what was typed.

sensitive

fields:
  api_token: { type: sensitive }

A secret sealed under the application key before it is stored and shown as a mask. The eye shows the stored value and writes <entity>.reveal to the audit log (settings.reveal on a settings screen); typing replaces the value whole, and a blank or the mask submitted back leaves it as it is. The column is text; lat crypt rotate re-seals it after a key rotation.

fields:
  service_key:
    type: sensitive
    file: true
    accept: [.json, .p12]
    max_size: 16kb
KeyDefaultDescription
filefalseThe secret is an uploaded file, sealed in the same text column.
acceptanyThe extensions an upload may have.
max_size64kbThe largest upload, in bytes or as 16kb, 1mb. At most 512kb.

A sealed file shows its name, size and fingerprint, has no Reveal, and is replaced by choosing another.

use laterite_core::SealedFile;

let sealed = record.get("service_key").and_then(|v| v.to_text()).unwrap_or_default();
let key = SealedFile::open(&crypt, "service_key", &sealed)?;
let json: serde_json::Value = serde_json::from_slice(&key.bytes)?;

id

fields:
  post_id: { type: id }

No keys. A record id held as a number, as a hidden input; a relation’s foreign key is one.

reference

fields:
  author_id: { type: reference, source: acme.authors }
KeyDefaultDescription
sourceA registered picker source. Required.

The column holds the chosen id as a number.

repeater

fields:
  links:
    type: repeater
    min_items: 1
    max_items: 10
    summary_field: label
    fields:
      label: {}
      url:   { input: url }
KeyDefaultDescription
fieldsThe row’s fields, a map like the form’s. Required. A field with no label shows its name.
min_items0The fewest rows: this many show from the start, and Remove is off at this count.
max_itemsnoneThe most rows: Add, the row’s add and Duplicate are off at this count.
displayautoauto, inline, list. auto: one field a row is compact; past 3 fields a row, rows collapse to the line naming them.
summary_fieldthe first fieldWhich field names a collapsed row.
expandedfalseList rows show open.
promptAddThe Add button’s label.
reordertrueEach row moves up and down.
duplicatetrueEach row copies into a new one beneath it.

A row of one field is compact: one line a row, each with add and remove, and always at least one line.

fields:
  aliases:
    type: repeater
    max_items: 5
    fields:
      name: { placeholder: "Another name" }

media

fields:
  cover_id: { type: media, mode: image }
  gallery:  { type: media, max: 6 }
KeyDefaultDescription
modefileimage offers images alone and shows thumbnails.
max1How many files the field holds; 0 is no limit.
publicfalseThe file is shown to people who are not signed in, so a private file is refused.

The columns it writes and the links it keeps: Media Field.

List Columns

Every built-in column type. The keys every column takes (label, width, labels, …) are on List Descriptor, and a type of your own is Writing a Column Type.

text

columns:
  title: { searchable: true }

The value as stored, or its entry under labels. The type when none is written; the search box looks in it.

datetime

columns:
  created_at: { type: datetime, align: right }

A date and time in the display timezone.

date

columns:
  published_on: { type: date }

A date in the display timezone.

time

columns:
  opens_at: { type: time }

A time of day in the display timezone.

boolean

columns:
  is_live: { type: boolean, width: 80px }
ValueShown as
1, trueYes
0, false, emptyNo

status_pill

columns:
  status: { type: status_pill, labels: [{ value: draft, label: Draft }, { value: live, label: Live }] }

A pill coloured by the value, lowercased with anything but letters and digits made a hyphen, and reading as its entry under labels.

columns:
  website:   { type: link, new_tab: true }
  instagram: { type: link, icon: instagram, text: "@{value|handle}", new_tab: true }
  order:     { type: link, url: "acme/orders/{id}/edit", text: "Open {code}" }
KeyDefaultDescription
urlthe valueThe address, with {value} for the cell’s value, {id} for the record’s and {column} for another column on the list. A value filled in is URL-encoded. An address with no scheme and no leading / is under the admin.
textthe valueWhat the link reads, with the same placeholders. "" shows the icon alone.
PlaceholderFills in
{value}, {id}, {column}The value as stored
{value|handle}The last part of a link’s path, without @: band from https://social.acme/@band
{value|host}A link’s domain, without www.: acme.com
iconnone
new_tabfalse
formatthe field’s
CaseShown as
http, https, mailto, tel or a / pathA link
Any other address (javascript:, data:)Text
A placeholder whose column is not on the list, or is emptyText
An empty value with no urlNothing

partial

A cell drawn by a template a module registers.

registry.add(PartialReg::new(
    "acme.stock_level",
    include_str!("../partials/stock_level.html"),
));
columns:
  stock: { type: partial, path: acme.stock_level }
{# partials/stock_level.html #}
{% if value | int < 5 %}<b style="color:var(--danger)">{{ value }} left</b>
{% else %}{{ value }} in stock{% endif %}
<small>{{ record.sku }}</small>
KeyDefaultDescription
pathThe partial’s registered name. Required; a name nobody registered stops the boot.
VariableHolds
valueThe cell’s stored value, as text.
recordEvery column on the list by name, as text, and id. A column hidden from the list is not in it.
columnThe column’s keys from the list file.

The template is MiniJinja. A value written with {{ }} is escaped as HTML; the template’s own markup is not. The column sorts, searches and exports by its stored value. A template that fails shows the value as text.

Filter Scopes

Every built-in filter type, with what it offers and what reaches the query. The keys every filter takes (label, default_value, permission) are on Filters.

boolean

filters:
  featured: { type: boolean }
OffersMatches
Yes or noRows where the column is true (1) or false (0).

select

filters:
  status:
    type: select
    options: [{ value: draft, label: Draft }, { value: live, label: Live }]
    default_value: live
  country: { type: select, options: acme.countries }
  state:   { type: select, options: acme.states, depends_on: country }
KeyDescription
optionsThe choices: a list of { value, label }, or the name of an option source. Required.
depends_onA filter, or a list of filters, whose values the source reads through OptionCx::values. When one changes, this filter’s choices are asked for again, and a value no longer offered is dropped.
OffersMatches
One of the declared valuesRows equal to it. A value not declared is dropped.

text

filters:
  author: { type: text }
OffersMatches
A text boxRows containing the text, folded the way the search box folds.

number

filters:
  views: { type: number }
OffersMatches
A number boxRows equal to the whole number. Anything else is dropped.

date

filters:
  created_at: { type: date }
OffersMatches
A date pickerRows on that YYYY-MM-DD day, whether the column holds a date or a timestamp.

Icons

The framework ships 215 icons. Name one in any descriptor that takes an icon: a settings item, a navigation entry, a resource.

SettingsItem::new("acme.blog", "Blog", fields).icon("newspaper")

An unknown name is refused when the application boots, with the nearest matches suggested.

Adding one that is not here

The set is a subset of upstream. A plugin registers what it needs:

registry.add(IconReg::new(
    "map-pin-house",
    include_str!("../assets/icons/map-pin-house.svg"),
));

It is namespaced to your module and referenced as vendor.package:map-pin-house.

Flags

Fillable icons are closed shapes that read correctly filled, for a state such as a favourited star. Filling is a render option, never part of the name: there is no star-solid.

Mirrored icons flip under a right-to-left layout. A clock does not mirror; a chevron does.

Brands are drawn solid, in the brand’s own shape. A plugin’s brand mark is registered with IconReg::new(name, svg).solid().

chrome (48)

Name
arrow-up-downmirrors in RTL
check
chevron-down
chevron-leftmirrors in RTL
chevron-rightmirrors in RTL
chevron-up
chevrons-leftmirrors in RTL
chevrons-rightmirrors in RTL
circle-alert
circle-checkfillable
circle-help
circle-x
columns-3
copy
download
ellipsis
ellipsis-vertical
external-linkmirrors in RTL
eye
eye-off
funnel
grip-vertical
history
info
layout-dashboard
layout-grid
listmirrors in RTL
loader-circle
log-inmirrors in RTL
log-outmirrors in RTL
menu
monitor
moon
panel-leftmirrors in RTL
pencil
plus
redo-2mirrors in RTL
refresh-cw
save
search
settings
sliders-horizontal
sun
trash-2
triangle-alert
undo-2mirrors in RTL
upload
x

people (12)

Name
contact
fingerprint
id-card
key
lock
lock-open
shield
shield-check
user
user-plus
user-round
users

content (37)

Name
bold
book-open
bookmarkfillable
braces
code
file
file-text
files
film
flagfillable
folder
folder-open
folder-plus
heading
heartfillable
image
images
italic
link
list-orderedmirrors in RTL
minus
music
newspaper
notebook-pen
notepad-text
paperclip
pinfillable
quotemirrors in RTL
square-pen
starfillable
strikethrough
table
tag
tags
type
underline
unlink

communication (11)

Name
at-sign
bellfillable
bell-off
bell-ring
mail
megaphone
message-circle
message-square
phone
rss
sendmirrors in RTL

commerce (25)

Name
badge-percent
banknote
briefcase
building
building-2
calculator
chart-bar
chart-line
chart-pie
coins
credit-card
gift
landmark
package
percent
receipt
scale
shopping-bag
shopping-cart
store
ticket
trending-downmirrors in RTL
trending-upmirrors in RTL
truck
wallet

time-place (12)

Name
alarm-clock
calendar
calendar-days
clock
compass
globe
home
map
map-pin
map-pinned
navigation
timer

technical (27)

Name
bluetooth
bot
bug
camera
cloud
cloud-download
cloud-upload
cpu
database
git-branch
hard-drive
laptop
mic
plug
printer
qr-code
server
smartphone
sparkles
tablet
terminal
video
wand-sparkles
webhook
wifi
workflow
zap

objects (28)

Name
activity
award
blocks
box
boxes
brush
check-checkfillable
circlefillable
component
crown
droplet
flame
gauge
hammer
layers
layout-template
leaf
lightbulb
paintbrush
palette
puzzle
rocket
squarefillable
square-checkfillable
target
trianglefillable
trophy
wrench

brands (15)

Name
apple
discord
facebook
github
google
instagram
pinterest
soundcloud
spotify
telegram
threads
tiktok
whatsapp
x-twitter
youtube

Bulk Import

A resource’s records imported from a CSV, each row written through the resource’s form, one commit a row, with a report. Built into the admin.

Let a resource be imported into

# descriptors/products.yaml
import: true
import:
  permission: acme.import_products
Resource::new("/products", "Products", list)
    .form(form)
    .permission("acme.manage_products")
    .import(ImportConfig::new())
[backend]
storage = "storage"
fn register(&self, registry: &mut Registry) {
    registry.add(DiskReg::new("private", Arc::new(LocalDisk::new("/srv/acme/private"))));
}
KeyDefaultDoes
import: trueoffMounts the pages at /admin/products/import and shows an Import button beside the list’s export menu.
import.permissionthe resource’sThe permission a user needs to import.
backend.storagestorageThe directory the uploaded file is kept under, in private, as a media record outside the library.
DiskReg named privatenoneKeeps the file on another disk.

A resource declaring import needs a form and a permission; either missing aborts boot naming the resource.

The delimiter is read off the file’s first line (comma, semicolon or tab) and can be set by hand. Files are read as UTF-8; a byte-order mark is accepted.

Start a run from code

use laterite_admin::import::{start, Duplicates, Match, RunSpec};

let products = ctx.form("/products").expect("the products resource");
let spec = RunSpec::new("/products", vec![Match::new(0, "sku"), Match::new(1, "name")])
    .duplicates(Duplicates::update("sku"))
    .media(payload_id);

let run = start(ctx.db(), products, actor, spec, disk.get(&path).await?).await?;

start records the run, detaches the work and returns the run’s id. The request that started it may end; the rows keep being written.

OptionDefaultDoes
RunSpec::new(resource, matches)The resource’s path as its descriptor declares it, and the column matches.
Match::new(column, field)File column column (from 0) fills field. A column may fill several fields.
.duplicates(Duplicates::skip(key))noneA row whose key is already there is passed over and noted.
.duplicates(Duplicates::update(key))noneA row whose key is already there updates that record; fields the file does not carry keep their values.
.keep_blank(bool)trueOn an update, a blank matched cell leaves the record’s value as it is. false clears the field.
.dry_run(bool)falseNothing is written; the counts say what an import would do.
.first_row_titles(bool)trueThe first row names the columns and is passed over.
.delimiter(u8)b','The byte between values.
.titles(vec)noneThe file’s titles; a later file with the same titles is proposed this matching.
.media(id)noneThe stored payload’s record, kept on the run.

start returns RunError::Spec for a match naming a field the form lacks, no matches, or a duplicates key no column feeds. A blank row is passed over.

Poll a run

use laterite_admin::import::{find, Status};

let run = find(ctx.db(), id).await?.expect("a run");
match run.status {
    Status::Queued => "waiting for a worker".to_string(),
    Status::Running => format!("{} rows so far", run.processed),
    Status::Done => format!("{} created, {} updated", run.created, run.updated),
    Status::Failed => run.failure.unwrap_or_default(),
}
FieldMeaning
statusQueued (pushed, no worker has taken it), Running, Done, or Failed (the run itself stopped; failure says why). A run whose worker stopped is failed by the queue after queue.retry_after_seconds.
processed, created, updated, skipped, errorsRow counts. On a dry run, what an import would do.
notesOne per message: row (the line in the file), kind (Error or Skipped), field, message (a Text, localized where it renders).
specWhat ran, dry_run included.
resource, media_id, actor_label, started_at, finished_atWhat ran, as recorded.

A refused row is a note; the next row still runs.

Writing a Plugin

lat make:plugin scaffolds a plugin crate; lat plugin add installs it.

lat make:plugin acme.blog            # blog-plugin/: Cargo.toml, src/lib.rs
lat make:plugin acme.blog --admin    # adds src/admin/
lat plugin add ./blog-plugin
ArgumentDescription
<ID>The module id, vendor.name. The crate is vendor-name.
--path <PATH>Where to create it. Default the current directory.
--adminScaffold the admin half: descriptors, screens, settings.

Mark the crate

Name its module, and declare the framework by version:

[package.metadata.laterite]
plugin = "acme.blog"

[dependencies]
laterite-core = "0.12"
laterite-admin = "0.12"

The dependency requirement is the compatibility statement. lat plugin add refuses a plugin built for another Laterite:

$ lat plugin add ../acme-legacy
Error: acme-legacy needs laterite-core ^0.2, and this application is on 0.5.0.

Never declare the framework by path. An application on a local checkout maps it with [patch.crates-io], which lat new writes in development mode.

Use the framework’s crates

use laterite_core::sea_query::{self, Alias, Expr, Iden, Query};
use laterite_core::serde_json::json;
use laterite_core::{minijinja, sqlx};
use laterite_admin::axum::Router;
CrateReach it at
sqlxlaterite_core::sqlx
sea-querylaterite_core::sea_query (with use, #[derive(Iden)] works)
serde_jsonlaterite_core::serde_json
minijinjalaterite_core::minijinja
axumlaterite_admin::axum
serdea dependency of the plugin’s own: serde = { version = "1", features = ["derive"] }

lat plugin sync, lat plugin check and lat doctor read the application’s dependency graph:

$ lat plugin sync
Dependencies:
  error sea-query is built in 2 versions (0.31.1 for acme-maps; 0.32.7 for the framework); values of one do not fit the other, so these cannot exchange them. Move the plugin onto the framework's version.
  warn  acme-maps depends on sea-query itself; reach it through `laterite_core::sea_query` so a version change on either side cannot split its types
  note  44 other crate(s) are built in more than one version, none crossing a plugin boundary (`lat plugin check` lists them)
FindingLevel
A crate whose types cross the boundary (sqlx, sea-query, serde_json, minijinja, axum, laterite-*) in two versionserror
Two plugins, or a plugin and the framework, linking the same native libraryerror
A plugin listing a re-exported crate itselfwarning
Any other crate in two versionsnote

Expose the module

At the crate root:

use laterite_core::{migration_set, BootCx, CoreResult, MigrationSet, Module, ModuleId, Registry};

migration_set! {
    module_id: "acme.blog",
}

pub fn module() -> Box<dyn Module> {
    Box::new(Plugin)
}

pub struct Plugin;

impl Module for Plugin {
    fn id(&self) -> ModuleId {
        ModuleId::new("acme.blog")
    }
    fn migrations(&self) -> MigrationSet {
        migrations()
    }
    fn register(&self, registry: &mut Registry) {
        // registry.add_resource(..);
        // registry.add_permission(..);
        // registry.add_settings(..);
    }
    async fn boot(&self, cx: &BootCx<'_>) -> CoreResult<()> {
        // A sweep, a seed or a check, with cx.db and cx.registry.
        Ok(())
    }
}
MethodRunsDescription
migrationsBefore register, in dependency order.Applies the module’s own migrations. See Migrations.
registerOnce every module has migrated.Contributes resources, settings models, permissions, menu entries, hooks.
bootOnce every module has registered, before anything is served.Anything that needs the database and the whole registry. An error quarantines the plugin.

Add a resource

lat make:resource article --field title:text --field body:text --field published:boolean

Scaffolds the entity’s migration, schema, store and admin screen, mounted at /articles. Field types: text, integer, boolean, datetime. See Resource Features and Hooks. --source content/articles keeps the records as files; see Records in Files.

Installing Plugins

A plugin is a crate compiled into the application. Installing one records it and rebuilds.

StateWhereChanging it costs
Which plugins are compiled inplugins/plugins.tomla rebuild
Which of them are enabledthe databasea restart

Add one

$ lat plugin add ../acme-blog-plugin
$ lat plugin add https://github.com/acme/blog-plugin
$ cargo build

A checkout outside the project is linked into plugins/, not copied. --as <folder> picks the folder name.

A plugin added from a git URL is vendored: its files are copied in without their .git folder, and source in the list records the URL.

In a static website (see Static Website) the first lat plugin add writes the site’s Cargo project, and only a plugin whose marker says static = true is accepted.

Edit the list

# plugins/plugins.toml
[[plugin]]
path = "acme-blog"

[[plugin]]
path = "acme-blog"
source = "https://github.com/acme/blog-plugin"
CommandDescription
lat plugin addRecords a plugin and syncs.
lat plugin removeDrops the entry. --delete removes the folder; a link only loses its link.
lat plugin syncRegenerates plugins-manifest/ from the list. Run after editing by hand.
lat plugin listPrints the plugins the application compiles in.
lat plugin checkChecks each installed plugin against the expected layout.
lat doctorChecks the list and the manifest agree.

Two entries resolving to one crate are refused.

Enable and disable

Settings → Plugins turns a compiled-in plugin off without a rebuild. The change applies at the next start: a disabled plugin’s migrations do not run, it contributes nothing, and anything depending on it is skipped. Its tables stay.

Resource Features and Hooks

A module mounts routes of its own under any resource that opts in, or changes another module’s resource before it mounts.

Mount a feature under a resource

use laterite_admin::axum::routing::get;
use laterite_admin::axum::Router;
use laterite_admin::routes::{ResourceFeature, ResourceFeatureReg, ResourceInfo, RouteCtx};

struct Archive;

impl ResourceFeature for Archive {
    fn mount(&self, ctx: &RouteCtx, resource: &ResourceInfo) -> Router {
        let form = resource.form.clone();
        Router::new().route("/", get(move || async move { form.entity().to_string() }))
    }
}

registry.add(ResourceFeatureReg::new("archive", Arc::new(Archive)));
# descriptors/products.yaml
archive: true
FieldMeaning
resource.pathThe resource’s path as declared, relative to the admin root (/products).
resource.base_pathWhere its list mounted (/admin/products).
resource.labelIts menu label.
resource.permissionThe permission the feature’s routes are gated by.
resource.formIts form, to write records through.

The routes mount at {base_path}/{key} behind the permission. A descriptor declaring a key nobody registered aborts boot naming the resource. The admin knows the import key; a new key needs the admin to carry it.

Change another module’s resource

registry.add_resource_hook(ResourceHook::new("/acme/blog/posts", |mut resource| {
    resource.list.columns.push(ListColumn::new("reviewed", "Reviewed").boolean());
    resource
        .relation(RelationConfig::has_many("notes", "Note", "post_notes", "post_id", notes_list, notes_form))
        .menu(Placement::new().under("acme.content"))
}));
KeyDoes
targetThe resource’s path as it mounts: /posts for an application’s, /acme/blog/posts for a plugin’s under its module base. One nobody declared aborts boot.
The closureTakes the resource as declared, returns it changed. Anything the builders set: columns, fields, relations, import, the palette source, the menu placement.
OrderHooks run in module order, before the resource mounts; each sees the previous one’s result.

Console Commands

A module adds a command to the application. lat <name> runs it from the project, after the application has booted.

Register a command

use std::sync::Arc;
use laterite_core::command::{Command, CommandCx, CommandError, CommandReg};
use laterite_core::t;

struct Greet;

#[async_trait::async_trait]
impl Command for Greet {
    async fn run(&self, cx: &CommandCx<'_>, args: &[String]) -> Result<(), CommandError> {
        let name = args.first().ok_or("usage: greet <name>")?;
        println!("Hello {name}, from {}", cx.storage_dir());
        Ok(())
    }
}

impl Module for AcmeBlog {
    fn register(&self, registry: &mut Registry) {
        registry.add(CommandReg::new("greet", t!("Greet someone"), Arc::new(Greet)));
    }
}
lat greet Ada
lat help-app
CommandReg::newDescription
nameThe word that runs it: lowercase letters, digits and hyphens.
aboutOne line in lat help-app.
commandWhat runs.
CommandCxGives
db()The application’s database, migrated.
registry()Every module’s registrations.
storage_dir()backend.storage.

Parse arguments

use clap::Parser;

#[derive(Parser)]
struct Args {
    name: String,
    #[arg(long)]
    loud: bool,
}

async fn run(&self, cx: &CommandCx<'_>, args: &[String]) -> Result<(), CommandError> {
    let args = Args::try_parse_from(std::iter::once("greet".to_string()).chain(args.iter().cloned()))?;
    println!("{}", if args.loud { args.name.to_uppercase() } else { args.name });
    Ok(())
}
CaseResult
run returns an errorThe message is printed and the binary exits non-zero.
A name the binary answers itself (serve, admin, routes, seed, build, publish, queue, schedule, help)The start aborts.
Two modules register one nameThe start aborts.
An unknown nameThe error lists every command.

The application’s main must call Bootstrap::run, as lat new writes it.

Abilities

An ability is one act a module declares by name, with a typed input and a permission, for any caller to run as the signed-in person.

Declare an ability

use laterite_admin::ability::{Ability, AbilityCx, AbilityError, AbilityHandler, Effect, Link, Outcome};
use laterite_admin::AdminRegistry;
use laterite_core::serde_json::Value;
use laterite_core::t;
use std::sync::Arc;

#[derive(serde::Deserialize, schemars::JsonSchema)]
struct AddLead {
    /// The person's full name.
    name: String,
    /// A phone number with its country code.
    phone: Option<String>,
}

struct AddLeadHandler;

#[laterite_core::strata::async_trait]
impl AbilityHandler for AddLeadHandler {
    async fn run(&self, cx: &AbilityCx<'_>, input: Value) -> Result<Outcome, AbilityError> {
        let lead: AddLead = laterite_core::serde_json::from_value(input)
            .map_err(|e| AbilityError::invalid(e.to_string()))?;
        let id = acme::leads::add(cx.db(), &lead.name, lead.phone.as_deref(), cx.actor())
            .await
            .map_err(|e| AbilityError::Failed(e.to_string()))?;
        Ok(Outcome::new(t!("Added the lead."))
            .link(Link::new(lead.name, format!("/admin/acme/crm/leads/{id}/edit"))))
    }
}

fn register(&self, registry: &mut laterite_core::Registry) {
    registry.add_ability(
        Ability::new("acme.crm.add_lead", t!("Add a lead"), Arc::new(AddLeadHandler))
            .describe(t!("Adds a person to the leads list."))
            .permission("acme.crm.leads.create")
            .input::<AddLead>()
            .sensitive(["phone"])
            .effect(Effect::Create),
    );
}
MethodSetsDefault
new(code, label, handler)the dotted code with the module’s id first, the name people see, the code behind itrequired
describewhat it does and when to use it, for a caller choosing among abilitiesnone
groupthe shelf it sits on in a cataloguethe code without its last segment
permissionthe permission a person needs to see and run itopen to every operator
input::<T>()the input as a type deriving schemars::JsonSchemano input
input_schema(value)the input as a JSON Schema objectno input
effectwhat running it doesEffect::Run
untrusted()marks the result as carrying text written by people outside the paneltrusted
sensitive([..])input fields left out of the audit entrynone
EffectMeaning
Readanswers a question and changes nothing
Createadds a record
Updatechanges a record
Deleteremoves a record
Sendsends something to a person outside the panel
Runany other change: publishing, importing, a rebuild

An ability with an effect other than Read names a permission. A doc comment on an input field is that field’s description in the schema.

Say what it would do

use laterite_admin::ability::{Draft, Preview};

async fn preview(&self, cx: &AbilityCx<'_>, input: &Value) -> Result<Preview, AbilityError> {
    let version = acme::documents::draft_version(cx.db(), input).await?;
    Ok(Preview::new(t!("Publishes the draft of Terms of Use."))
        .record(Link::new(version.title, version.href))
        .count(1))
}
MethodSets
Preview::new(summary)the act in a sentence
record(link)a record the act touches
count(n)how many records it touches
draft(Draft::new(path, id, values))a resource’s form, filled in, for the person to save

Answer from the handler

ReturnWhen
Ok(Outcome::new(message))it ran; add .link(..) for records and .data(..) for a result as JSON
Ok(Outcome::new(message).go(href))it ran, and the person is taken to href, a path on the site
Err(AbilityError::Refused(text))it declined, with a reason the person reads
Err(AbilityError::invalid(message))the input is wrong in a way the schema cannot state
Err(AbilityError::Failed(message))it broke; the message goes to the log

AbilityCx gives db(), ctx(), user() and actor(). Pass actor() to FormHandle::create and FormHandle::update, and to AuditEntry::new.

Run an ability

use laterite_core::serde_json::json;

let abilities = ctx.abilities();

for ability in abilities.for_user(&user) {
    println!("{} ({})", ability.code(), ability.effect_kind().as_str());
}
let found = abilities.search(&user, "add a lead", 5);

let preview = abilities
    .preview(&user, "acme.crm.add_lead", &json!({ "name": "Asha Rao" }), None)
    .await?;
let outcome = abilities
    .run(&user, "acme.crm.add_lead", json!({ "name": "Asha Rao" }), Some("acme.assistant"))
    .await?;
MethodAnswers
for_user(&user)every ability the person may run
get(&user, code)one ability, when the person may run it
search(&user, words, limit)the abilities matching the words, best first
preview(&user, code, &input, channel)the handler’s Preview
run(&user, code, input, channel)the handler’s Outcome

channel names what acts for the person (acme.assistant), or None. The Audit Log shows it under Through.

ErrorCause
AbilityError::Unknown(code)no ability has the code, or the person lacks its permission
AbilityError::Invalid(faults)the input does not fit the schema; one message per fault

A run with an effect other than Read writes an ability.run audit entry.

Act for a person

use laterite_admin::ability::Confirm;

let abilities = ctx.abilities();
const CHANNEL: &str = "acme.assistant";

for (ability, confirm) in abilities.offered(&user).await? {
    println!("{} ({})", ability.code(), confirm.as_str());
}

match abilities.confirm(&user, "acme.crm.add_lead").await? {
    Confirm::Auto => {
        abilities.run(&user, "acme.crm.add_lead", input, Some(CHANNEL)).await?;
    }
    _ => {
        let preview = abilities
            .preview(&user, "acme.crm.add_lead", &input, Some(CHANNEL))
            .await?;
        // Show the preview; run once the person agrees.
    }
}
AnswerMeansDefault for
Confirm::Autorun without askingEffect::Read
Confirm::Askshow the preview, run when the person agreesevery other effect
Confirm::Offnot offered: confirm, preview and run answer AbilityError::UnknownEffect::Delete, Effect::Send

A call with channel set to None is the person themself and is not asked.

use laterite_admin::ability::{Confirm, OwnPolicy, PanelPolicy, PolicyRule};
use laterite_admin::settings::store;

store::save(ctx.db(), &PanelPolicy {
    rules: vec![
        PolicyRule::new("effect:delete", Confirm::Ask),
        PolicyRule::new("acme.crm", Confirm::Ask),
        PolicyRule::new("acme.crm.add_lead", Confirm::Auto),
    ],
}).await?;

store::save_for(ctx.db(), user.user.id, &OwnPolicy {
    rules: vec![PolicyRule::new("acme.crm.add_lead", Confirm::Ask)],
}).await?;
RuleCoversWins over
acme.crm.add_leadthat abilityevery other rule
acme.crmevery ability whose code starts acme.crm.a shorter start, an effect
effect:createevery ability with that effectthe default
Set byWhereReach
An administrator holding backend.manage_abilitiesSettings, Abilities (PanelPolicy)the furthest anyone goes
Each personPreferences, Acting for me (OwnPolicy)tighter than the panel’s rule, or as loose as it and no looser

A run through a channel records its answer as confirm in the audit entry.

Offer a resource’s records

entity: posts
path: /posts
title: Posts
permission: acme.posts.manage
abilities:
  describe: Blog posts. A post has a title, a body in markdown and a publish date.
  update: false
  hide: [internal_notes]
use laterite_admin::records::RecordAbilities;

Resource::new("/posts", "Posts", list)
    .abilities(RecordAbilities::new().describe(t!("Blog posts.")).hide(["internal_notes"]));
KeySetsDefault
abilities: falsekeeps the resource out of every record abilityoffered
describewhat the records are, for a caller choosing where to looknone
createa new record may be draftedtrue, where the list is creatable
updatea change may be draftedtrue
deletea record may be deletedtrue, where the list is deletable
hidefields and columns kept from a callernone
untrustedthe records carry text written by people outside the panelfalse
AbilityInputAnswers
backend.records.kindsresource (optional)the kinds open to the person; one kind with its fields, columns, filters and sorts
backend.records.findresource, search, filters, sort, dir, limitmatching rows with their ids, 25 at most
backend.records.openresource, search, filters, sort, dirthe list’s address with all of it set, as Outcome::go
backend.records.readresource, idone record’s field values
backend.records.createresource, valuespreview: the filled form as a Draft; run: the new id
backend.records.updateresource, id, valuespreview: the changed form as a Draft; run: the id
backend.records.deleteresource, idpreview: the record named; run: the id, moved to the trash on a soft_delete resource
{ "resource": "/posts", "filters": { "status": "live", "views_min": 1000 }, "sort": "views", "dir": "desc" }

filters names the list’s own filters, the ones the person may use. resource is the resource’s path. Each ability asks for the resource’s permission, and a create or an update for its permissions.create or permissions.update, and a delete for permissions.delete. password and sensitive fields are never read or set.

Act for a person in your own writes

use laterite_core::Actor;

let actor = Actor::from(&user).through("acme.assistant");
form.create(values, &actor).await?;

Actor::channel() reads it back in a model listener.

Surfaces

A surface is a screen describing itself to a caller: its controls, the parts inside it and what each part does.

Describe a component

use laterite_admin::ability::{AbilityCx, AbilityError, Outcome};
use laterite_admin::surface::{Control, Part, Request, Surface, READ, SHOW};
use laterite_admin::AdminRegistry;
use laterite_core::serde_json::json;
use laterite_core::{t, Text};
use std::sync::Arc;

struct Overview;

#[laterite_core::strata::async_trait]
impl Surface for Overview {
    fn path(&self) -> &str {
        "/acme/overview"
    }

    fn label(&self) -> Text {
        t!("Overview")
    }

    fn permission(&self) -> Option<&str> {
        Some("acme.reports.view")
    }

    async fn parts(&self, _cx: &AbilityCx<'_>) -> Result<Part, AbilityError> {
        Ok(Part::new("overview", t!("Overview")).act(SHOW).part(
            Part::new("orders_by_day", t!("Orders by day"))
                .describe(t!("How many orders arrived each day."))
                .control(
                    Control::new("range", t!("Period"), "date_range")
                        .value(json!({ "from": "2026-10-01", "to": "2026-10-31" })),
                )
                .control(Control::new("group_by", t!("Group by"), "select").values(["day", "week"]))
                .act(READ),
        ))
    }

    async fn act(&self, cx: &AbilityCx<'_>, request: &Request) -> Result<Outcome, AbilityError> {
        if request.act == SHOW {
            return Ok(Outcome::new(t!("Opened the overview.")).go("/admin/acme/overview"));
        }
        let from = request.set["range"]["from"]
            .as_str()
            .ok_or_else(|| AbilityError::invalid("set/range: give `from` and `to`"))?;
        let points = acme::orders::by_day(cx.db(), from, request.text("group_by")).await?;
        Ok(Outcome::new(t!("The orders by day.")).data(json!({ "points": points })))
    }
}

fn register(&self, registry: &mut laterite_core::Registry) {
    registry.add_surface(Arc::new(Overview));
}
MethodAnswersDefault
pathwhere the screen is under the admin root; it names the surfacerequired
labelwhat a person calls the screenrequired
describewhat the screen is fornone
permissionthe permission a person needs to see itevery signed-in person
partsthe screen as this person sees itrequired
actsets the controls a request names and does its actrequired

Build the description

PartSets
Part::new(name, label)the name a caller uses, the name a person reads
describe(text)what the part shows
control(control)something a caller sets
part(part)a component inside this one
act(name)something the part does: SHOW, READ, or a word of its own
ControlSets
Control::new(name, label, kind)the name, the label, and text, number, boolean, date, date_range, select or a word of its own
describe(text)what it narrows or changes
values([..])the fixed set of values it takes
value(value)what it is set to now
ActDoes
SHOW (show)answers Outcome::go with the screen’s address, the controls set
READ (read)answers Outcome::data with what the part holds

Read a request

let part: &[String] = &request.part;      // ["orders_by_day"]
let act: &str = &request.act;             // "read"
let grouping = request.text("group_by");  // Some("day")
let range = &request.set["range"];        // { "from": .., "to": .. }
FieldHolds
partthe names from the surface down to the part; empty for the surface itself
actan act that part lists
setthe controls to set, by name; each one the part lists

Return AbilityError::invalid("set/range: ..") for a value the control does not take.

Call a surface

use laterite_core::serde_json::json;

let abilities = ctx.abilities();
let screens = abilities.run(&user, "backend.screens.list", json!({}), None).await?;
let described = abilities
    .run(&user, "backend.screens.describe", json!({ "screen": "/acme/overview" }), None)
    .await?;
let read = abilities
    .run(&user, "backend.screens.act", json!({
        "screen": "/acme/overview",
        "part": "orders_by_day",
        "act": "read",
        "set": { "range": { "from": "2026-11-01", "to": "2026-11-15" }, "group_by": "day" }
    }), None)
    .await?;
AbilityInputAnswers
backend.screens.listnoneevery screen open to the person: screen, label, describe
backend.screens.describescreenits controls, parts and acts
backend.screens.actscreen, part (names joined with /), set, actthe act’s Outcome
{
  "screen": "/acme/overview", "name": "overview", "label": "Overview", "acts": ["show"],
  "parts": [{
    "name": "orders_by_day", "label": "Orders by day", "acts": ["read"],
    "controls": [
      { "name": "range", "label": "Period", "kind": "date_range",
        "value": { "from": "2026-10-01", "to": "2026-10-31" } },
      { "name": "group_by", "label": "Group by", "kind": "select", "values": ["day", "week"] }
    ]
  }]
}

Add a surface while mounting

impl Screen for Sales {
    fn mount(&self, ctx: &RouteCtx) -> Router {
        let board = Arc::new(self.board());
        ctx.add_surface(board.surface("/acme/sales", t!("Sales")));
        Router::new().nest_service("/board", board.routes(ctx))
    }
}
CallWhen
registry.add_surface(surface)in register, for a surface known then
ctx.add_surface(surface)in Screen::mount, for one built there; the same path replaces
board.surface(path, label)a board and its widgets as a surface

Lists

Every resource that offers record abilities is a surface named by its path.

ControlIs
searchthe list’s search
each filter by its keythat filter, with its values for a select
sort, dira sortable column, and asc or desc
{ "screen": "/posts", "act": "show", "set": { "status": "live", "views_min": 1000, "sort": "views", "dir": "desc" } }

Settings pages

Every settings page with fields is a surface at its page’s path, behind the page’s permission.

ControlIs
each field by its namethe field, with its value as stored; a person’s own for a per-person page
ActAnswers
showthe page’s address
readthe stored values by field name

A password or sensitive field is never named. A request that sets a control is refused: a setting is changed on its page.

Palette Modes

A palette mode is a tab in the command palette (Ctrl+K, Cmd+K) that posts what a person types to a route of yours and shows the markup it answers.

Add a mode

use laterite_admin::palette::PaletteMode;
use laterite_admin::AdminRegistry;
use laterite_core::t;

fn register(&self, registry: &mut laterite_core::Registry) {
    registry.add_palette_mode(
        PaletteMode::new("acme.lookup", t!("Look up"), "/acme/lookup/ask")
            .placeholder(t!("An order number"))
            .prefix('#')
            .permission("acme.orders.view")
            .live(),
    );
}
MethodSetsDefault
new(code, label, path)the dotted code with the module’s id first, the tab’s name, the route under the admin rootrequired
placeholderthe hint in the empty boxnone
prefixa character that, typed first, switches to the modenone
permissionthe permission a person needs to be offered the modeevery signed-in person
live()posts as the person typesposts on Enter

Answer the palette

use axum::{response::Html, routing::post, Form, Router};

#[derive(serde::Deserialize)]
struct Asked {
    q: String,
}

async fn ask(Form(asked): Form<Asked>) -> Html<String> {
    let number: u64 = asked.q.trim().parse().unwrap_or_default();
    Html(format!(
        r#"<ul class="lat-palette__list" role="listbox">
  <li><a class="lat-palette__hit" role="option" href="/admin/acme/orders/{0}">
    <span class="lat-palette__label">Order {0}</span>
    <span class="lat-palette__hint">Open</span>
  </a></li>
</ul>"#,
        number
    ))
}

fn mount(&self) -> Router {
    Router::new().route("/ask", post(ask))
}

The route is a screen mounted at the mode’s path. The post carries the form field q.

MarkupDoes
class="lat-palette__list" with lat-palette__hit linksa result list the arrow keys walk and Enter opens
class="lat-palette__empty"a line for no result
class="lat-palette__card"a form, a card or a result with a title
data-palette-raise on the answer’s rootmoves the palette to the top of the screen and widens it
data-palette-focus on one controltakes the focus when the answer arrives
hx-target="closest .lat-palette__canvas"swaps the next answer into the same panel
<form class="lat-palette__card" data-palette-raise
      hx-post="/admin/acme/lookup/refund"
      hx-target="closest .lat-palette__canvas" hx-swap="innerHTML">
  <h2 class="lat-palette__title">Refund order 1042</h2>
  <p class="lat-palette__summary">Returns 40.00 USD to the card.</p>
  <div class="lat-actions">
    <button class="lat-btn lat-btn--danger" type="submit" data-palette-focus>Refund</button>
  </div>
</form>

List the modes

curl -b cookies.txt https://acme.com/admin/palette/modes
[
  { "code": "backend.do", "label": "Do", "placeholder": "What do you want to do?",
    "prefix": ">", "url": "/admin/palette/do", "live": true },
  { "code": "acme.lookup", "label": "Look up", "placeholder": "An order number",
    "prefix": "#", "url": "/admin/acme/lookup/ask", "live": true }
]

The Do mode

backend.do (prefix >) lists the abilities a person may run and walks one through its input, its preview and its result.

AbilityIn Do
Input of strings, numbers, booleans and enum choicesoffered, one control per property
Input with an object or an arrayleft out
Effect::Readruns when chosen
Any other effectshows its Preview, then runs on confirmation
Effect::Delete, Effect::Sendthe confirmation is a danger button
backend.records.*left out

A property’s title is its label and its doc comment the help under it. A name or a choice with no title reads as words: found_on_site shows as “Found on site”.

Admin Screens

A module mounts a screen inside the admin for what a list and a form cannot express: an import wizard, a report, a diff view.

Take axum from the framework

use laterite_admin::axum::{routing::get, Router};
use laterite_core::strata::async_trait;

Never add axum or async-trait to a plugin’s Cargo.toml.

Mount an admin screen

use laterite_admin::routes::{RouteCtx, Screen, ScreenReg};

struct Importer;

impl Screen for Importer {
    fn mount(&self, ctx: &RouteCtx) -> Router {
        let db = ctx.db().clone();
        Router::new()
            .route("/", get(upload_form).post(run_import))
            .route("/report", get(move || show_report(db.clone())))
    }
}

fn register(&self, registry: &mut Registry) {
    registry.add_screen(
        ScreenReg::new("/import", "acme.import", Arc::new(Importer))
            .in_menu(t!("Import places")),
    );
}
ScreenRegDescription
new(path, permission, screen)path sits under the module’s identity: acme.places at /import serves /admin/acme/places/import. permission is required and enforced before the handler runs.
.in_menu(label)Adds it to the main menu. Without it the screen still mounts, reached by link.

The screen runs behind the session, CSRF protection and the error pages.

Render a page in the admin

use askama::Template;
use laterite_admin::axum::{Extension, Router};
use laterite_admin::html::Markup;
use laterite_admin::{AdminError, Shell};
use laterite_core::t;

#[derive(Template)]
#[template(path = "places.html")]
struct PlacesTemplate<'a> {
    shell: &'a Shell,
    rows: Vec<String>,
}

async fn places(Extension(shell): Extension<Shell>) -> Response {
    let body = PlacesTemplate { shell: &shell, rows: vec![] };
    match Markup::from_template(&body) {
        Ok(body) => shell.page(&t!("Places"), body),
        Err(e) => AdminError::Internal(e.into()).into_response(),
    }
}
<div class="lat-card">
  <form method="post" action="/admin/places">
    <input type="hidden" name="_csrf" value="{{ shell.csrf_token() }}">
    <button class="lat-btn lat-btn--primary" type="submit">{{ shell.t("Save") }}</button>
  </form>
</div>
MethodDoes
shell.page(&title, body)The body inside the chrome: nav, flash messages, assets, the title as the heading.
shell.t("Save"), shell.tt(&text)A string, or a Text, in the user’s locale.
shell.csrf_token()The request token for a form the template builds. First in an upload form.
shell.datetime(&utc)An RFC 3339 timestamp in the user’s timezone.
shell.base()The admin mount, for a link into the panel.

The admin’s stylesheet is already on the page: lat-card, lat-table, lat-fields, lat-field, lat-input, lat-select, lat-check, lat-facts, lat-actions, lat-btn, lat-alert, lat-help, lat-status. A SessionHandle extension carries push_flash; an AdminError renders the styled 404, 403 or 500. Headings, dialogs, split panes and chrome builders are on Page Layout.

Choose where it mounts

fn admin_base(&self) -> Option<&'static str> { Some("/places") }
[backend.paths]
"acme.places" = "/geography"
"acme.places/import" = "/geography/bulk-upload"

The deployment has the last word. Two modules on one path, or one on a framework screen, abort the boot naming both.

ctx.url("/report")      // "/admin/places/import/report", wherever it mounted
ctx.base_url()          // the site origin, from app.url or the bind address

base_url is for a URL a route emits: a sitemap <loc>, a canonical, a feed entry. Never build one from the Host header.

Add middleware

fn mount(&self, _ctx: &RouteCtx) -> Router {
    Router::new()
        .route("/", get(robots_txt))
        .layer(CompressionLayer::new())
}

Read other modules’ contributions

pub struct FeedReg {
    pub name: String,
}

impl PublicRoute for Feeds {
    fn mount(&self, ctx: &RouteCtx) -> Router {
        let feeds: Vec<&FeedReg> = ctx.contributions::<FeedReg>();
        // ...
    }
}

Any Send + Sync type another module registers. Contributions the framework consumes itself (resources, screens, settings, permissions, persisters, listeners, column types, public routes) are not visible here.

Write through a resource’s form

use std::collections::HashMap;
use laterite_admin::persist::SaveError;
use laterite_core::Actor;

impl Screen for Importer {
    fn mount(&self, ctx: &RouteCtx) -> Router {
        let products = ctx.form("/products").expect("the products resource");
        Router::new().route("/run", post(move || {
            let products = products.clone();
            async move {
                let actor = Actor::system("acme.import");
                let mut row = HashMap::new();
                row.insert("sku".to_string(), "A-100".to_string());
                row.insert("name".to_string(), "Anvil".to_string());
                match products.create(row, &actor).await {
                    Ok(id) => format!("created {id}"),
                    Err(SaveError::Invalid(bag)) => format!("refused: {bag:?}"),
                    Err(SaveError::Failed(e)) => format!("failed: {e}"),
                }
            }
        }))
    }
}

ctx.form(path) takes the resource’s path as its descriptor declares it, relative to the admin root, and is None when nothing with a form mounts there.

MethodDoes
create(data, &actor)Validates data as a submission, saves a new record through the form’s field types, listeners and persister, and returns its id.
update(id, data, &actor)The same as an edit of the record id. Every field is written; one left out of data is written blank.
entity(), id_field()The table and its primary key column.
fields()The declared fields, in order; data is keyed by their names.

SaveError::Invalid carries the per-field messages a refused submit shows; SaveError::Failed is the write failing. The audit log records the actor.

Public Routes

A module mounts an endpoint outside the admin: a feed, a robots.txt, a webhook. No session, no permission, no admin chrome.

Mount a public route

use laterite_admin::axum::{routing::get, Router};
use laterite_admin::routes::{PublicRoute, PublicRouteReg, RouteCtx};

struct Robots;

impl PublicRoute for Robots {
    fn mount(&self, _ctx: &RouteCtx) -> Router {
        Router::new().route("/", get(robots_txt))
    }
}

registry.add_public_route(PublicRouteReg::new("/robots.txt", Arc::new(Robots)));
PublicRouteRegDescription
new(path, route)path is literal, never namespaced. A route inside the admin mount is refused.

A POST must come from the site’s own origin. A route that authenticates each request itself (an API token, a signed webhook) leaves that check:

registry.add_public_route(
    PublicRouteReg::new("/api/capture", Arc::new(Capture)).skip_origin_check(),
);
PublicRouteRegDescription
skip_origin_check()The path and everything below it skip the origin check. The route verifies each request.

A path can also be listed in backend.origin_check_except. See Admin. ctx.url, ctx.base_url, middleware and other modules’ contributions work as on an admin screen.

Page Layout

The heading, side panel, dialogs, split panes and chrome builders a contributed screen composes its page from.

Head a page

use laterite_admin::PageHead;

let actions = Markup::from_template(&ActionsTemplate { shell: &shell })?;
shell.page_with(
    PageHead::new(t!("Places")).back(t!("Regions"), ctx.url("")).actions(actions),
    body,
)
<a class="lat-btn lat-btn--secondary lat-btn--sm" href="{{ export_href }}">{{ shell.t("Export") }}</a>
<details class="lat-menu">
  <summary class="lat-btn lat-btn--secondary lat-btn--sm">{{ shell.t("Manage") }} &#9662;</summary>
  <div class="lat-menu__panel">
    <button type="button" data-lat-dialog="new-place">{{ shell.t("New place") }}</button>
    <div class="lat-menu__divider"></div>
    <form method="post" action="{{ purge_href }}"><input type="hidden" name="_csrf" value="{{ shell.csrf_token() }}"><button class="is-danger" type="submit" data-lat-confirm='{{ shell.t("Purge every place?") }}'>{{ shell.t("Purge") }}</button></form>
  </div>
</details>
MethodDoes
PageHead::new(title)The heading.
.back(label, href)A link above the heading to the page this one sits under.
.actions(markup)Controls in the band under the heading: buttons, a details.lat-menu, dialog openers.
.aside(label, markup)A context side panel beside the body, folded under label on a narrow window.
.assets(assets)Scripts and styles the page needs, such as CODE_EDITOR_ASSETS.
shell.page_with(head, body)The body under that head, inside the chrome.

Add a side panel

let panel = Markup::from_template(&RegionsTemplate { shell: &shell, regions })?;
shell.page_with(
    PageHead::new(t!("Places")).aside(t!("Regions"), panel),
    body,
)
<nav class="lat-pane" aria-label='{{ shell.t("Regions") }}'>
  <ul class="lat-nav">
    {% for r in regions %}<li><a class="lat-nav__item{% if r.active %} is-active{% endif %}" href="{{ r.href }}">{{ r.name }}</a></li>{% endfor %}
  </ul>
</nav>

Open a form in a dialog

<button type="button" class="lat-btn lat-btn--primary lat-btn--sm" data-lat-dialog="new-place">{{ shell.t("New place") }}</button>
<button type="button" class="lat-btn lat-btn--ghost lat-btn--sm" data-lat-dialog="new-place" data-lat-dialog-set="kind=city">{{ shell.t("New city") }}</button>

<dialog class="lat-dialog" id="new-place">
  <form method="post" action="{{ base }}">
    <div class="lat-dialog__head"><h2>{{ shell.t("New place") }}</h2><button type="button" class="lat-dialog__close" data-lat-dialog-close aria-label='{{ shell.t("Close") }}'>&times;</button></div>
    <div class="lat-dialog__body">
      <input type="hidden" name="_csrf" value="{{ shell.csrf_token() }}">
      <div class="lat-field">
        <label class="lat-field__label" for="kind">{{ shell.t("Kind") }}</label>
        <select class="lat-input lat-select" id="kind" name="kind"><option value="city">{{ shell.t("City") }}</option></select>
      </div>
      <div class="lat-field">
        <label class="lat-field__label" for="name">{{ shell.t("Name") }}</label>
        <input class="lat-input" id="name" name="name" required autofocus>
      </div>
    </div>
    <div class="lat-dialog__actions"><button class="lat-btn lat-btn--ghost" type="button" data-lat-dialog-close>{{ shell.t("Cancel") }}</button><button class="lat-btn lat-btn--primary" type="submit">{{ shell.t("Create") }}</button></div>
  </form>
</dialog>
AttributeOnDoes
data-lat-dialog="id"Any controlOpens the dialog.lat-dialog with that id and focuses its first field.
data-lat-dialog-set="field=value;other=value"The openerFills the named fields before opening.
data-lat-dialog-closeA control insideCloses the dialog. Escape and a click on the backdrop close it too.
.lat-dialog--wideThe dialogA wider dialog.

Split a screen

<div class="lat-split">
  <nav class="lat-pane">
    <div class="lat-pane__head">{{ shell.t("Regions") }}<button type="button" class="lat-btn lat-btn--ghost lat-btn--sm lat-btn--icon" data-lat-dialog="new-region">{{ shell.icon("plus")|safe }}</button></div>
    <ul class="lat-nav">
      <li><a class="lat-nav__item is-active" href="{{ href }}"><span class="lat-nav__label">{{ shell.t("North") }}</span><span class="lat-nav__meta">12</span></a></li>
    </ul>
  </nav>
  <div class="lat-pane">
    <div class="lat-pane__bar"><nav class="lat-breadcrumb"><a href="{{ base }}">{{ shell.t("All") }}</a></nav><form method="get" action="{{ base }}"><input class="lat-input lat-listbar__search" type="search" name="q"></form></div>
    <div class="lat-pane__body">{{ content|safe }}</div>
    <div class="lat-pane__foot"><button class="lat-btn lat-btn--primary" type="submit">{{ shell.t("Save") }}</button></div>
  </div>
</div>
ClassRenders
lat-splitA pane beside the content inside a body; lat-split--aside puts the pane after the content. One column on a narrow window. For a panel beside the whole page, PageHead::aside above.
lat-paneA framed block; lat-pane__head, lat-pane__bar, lat-pane__body, lat-pane__foot stack inside it.
lat-nav, lat-nav__item, .is-activeA list of links in a pane, with lat-nav__label and lat-nav__meta.
shell.icon(name)An icon from the framework’s set, inline.

Compose chrome

use laterite_admin::ui::{Badge, Button, Card, Toolbar};

let body = Toolbar::new("Reports")
    .button(Button::link("New report", format!("{}/reports/new", ctx.admin_path())).primary())
    .button(Button::post("Rebuild", format!("{}/reports/rebuild", ctx.admin_path())).confirm("Rebuild every report?"))
    .render(&shell);
let card = Card::new(Markup::from_override(table_html)).render();
let state = Badge::new("Stale").render(&shell);
ElementBuildersRenders
Button::link(label, href).primary(), .danger(), .ghost(), .small(), .icon(name)A link styled as a button.
Button::post(label, action)The same, and .confirm(question)A form that posts with the request token, asking first when confirm is set.
Toolbar::new(title), Toolbar::section(title).button(..)A page or section heading, its buttons in the band under it.
Badge::new(label)A small label.
Card::new(markup)The panel’s framed block around what it is given.

Put a checklist on a screen

use laterite_admin::checklist::{Checklist, Choice, Expand, Offer};
use laterite_core::Translator;

let list = Checklist::new("Channels")
    .choice(Choice::new("channel", "email", "Email").checked(true))
    .group("Chat", vec![
        Choice::new("channel", "slack", "Slack").note("One workspace").into(),
        Choice::new("channel", "teams", "Teams").locked(true).into(),
    ])
    .select_all(Offer::Auto)
    .search(Offer::Never)
    .expand(Expand::All);

// `Markup`, for a template's `|safe` slot
let html = list.render(&Translator::new("en"));
BuilderDoes
Choice::new(name, value, label)One box, submitted as name=value.
.note(..), .code(..)A second line under the label; an identifier beside it.
.checked(..), .locked(..)Ticked; shown and not changeable.
.group(label, entries)A heading over entries of its own, nested to any depth.
.select_all(..), .search(..), .expand(..)The defaults listed under Behaviours.
.read_only(true)Every box locked.
.view(&translator)The resolved list as a serialisable value, for a field type’s view-model.

JavaScript API

The window.lat helpers a contributed screen or widget calls, the events every island announces, and the attributes that join a form of your own in.

Raise a message from script

window.lat.flash('Import finished.', 'success');   // or 'error', which stays until dismissed

Confirm before acting

<button type="submit" data-lat-confirm="Delete the selected records? This cannot be undone.">
  Delete
</button>

Ask from script

lat.confirm('Archive 12 articles?', { go: 'Archive', cancel: 'Keep', focus: 'cancel' }, function (yes) {
  if (yes) archive();
});
LabelDoes
goNames the confirming button. Default OK.
cancelNames the other. Default Cancel, localized.
focus'cancel' opens with the cursor on it. Default: the confirming button.

Join a form in

<form method="post" action="/admin/acme/import" data-lat-widget="form" data-lat-focus="first">
AttributeDoes
data-lat-widget="form"Asks before leaving with changes unsaved.
data-lat-refusedThe form holds a submission that was not saved: it opens changed, with the cursor in the first field carrying an error.
data-lat-focusfirst opens with the cursor in the first field; off leaves it alone.
data-lat-confirm-leave="off"Never asks.
data-lat-counterOn a control with maxlength: auto or on.
data-lat-grow="off"On a textarea: keeps the height it was given.
data-lat-preset, data-lat-preset-typeOn a field’s wrapper: the field followed and the shape (slug, url, file, exact).
data-lat-trigger-action, data-lat-trigger-field, data-lat-trigger-conditionOn a field’s wrapper: the dependency, as Field Dependencies spells it.

Keep Enter inside a widget

<div data-lat-widget="acme-lookup" data-lat-enter-scope data-lat-enter-target=".acme-lookup__go">
  <input type="search" name="q">
  <button type="button" class="acme-lookup__go">Look up</button>
</div>
AttributeDoes
data-lat-enter-scopeOn the root of a widget holding an input: Enter acts there and never submits the form around it.
data-lat-enter-target="<selector>"The button Enter presses inside that scope. Without a target, Enter does nothing.

Listen and drive

Every island announces what it does as a DOM event named lat:<component>:<event>, bubbling from its root. Server-side facts are on the event bus.

var stop = lat.on('repeater:added', function (detail, event) {
  console.log(detail.count, 'rows; the new one is', detail.row);
});

// A `before-` event is cancelable: this caps a repeater at five rows.
lat.on('repeater:before-add', function (detail, event) {
  if (detail.count >= 5) event.preventDefault();
});

// Drive an island through its controller.
lat.get(document.querySelector('[data-lat-widget="repeater"]')).add();

// A rich editor: the same three, plus the engine for anything else.
var rich = lat.get(document.querySelector('[data-lat-widget="richeditor"]'));
rich.editor.commands.insertContent('<p>Hello</p>');

// A markdown editor: the same, plus the Preview tab.
lat.get(document.querySelector('[data-lat-widget="markdown"]')).preview();

// A code editor: read, replace, focus.
var code = lat.get(document.querySelector('[data-lat-widget="codeeditor"]'));
code.set(code.get().trim());
code.focus();
EventDetailCancelable
repeater:before-addcountYes
repeater:addedrow, index, countNo
repeater:before-removerow, index, countYes
repeater:removedindex, countNo
repeater:movedrow, from, to, countNo
repeater:duplicatedrow, index, countNo
ref-picker:changedid, label, previousNo
ref-picker:clearedpreviousNo
selection:changedids, countNo
checklist:changedvalues, count, totalNo
flash:showntext, levelNo
flash:dismissedtextNo
confirm:openedtextNo
confirm:confirmed, confirm:cancelledNoneNo
copy:copiedvalueNo
reveal:shown, reveal:hiddenNoneNo
preset:filledfrom, valueNo
trigger:changedfield, metNo
ControllerMethods
Repeateradd(), remove(index), move(from, to), duplicate(index), count()
Record picker, searched selectvalue(), label(), choose({ id, label }), clear()
Checklistvalues(), count(), set(values), all(), none(), search(text)
Formchanged(), settle(): takes the form as it stands for saved
Password revealshow(), hide()
HelperDoes
lat.on(name, handler)Listens page-wide, swapped content included. Returns the function that stops listening.
lat.emit(el, name, detail, cancelable)Announces lat:<name> from el. Returns false when a listener cancelled it.
lat.get(el)The controller of the island at or around el.
lat.scan(root)Starts the islands in markup a script added. Swapped content starts without it.
lat.confirm(text, labels, done)Asks in the admin’s dialog. done hears true or false.
lat.flash(text, level)Raises a message: success, or error, which stays until dismissed.
lat.assets.ensure(url)Loads a stylesheet or script once.

Put a code editor on a contributed screen

<div data-lat-widget="codeeditor" data-language="yaml" style="--rows:16">
  <textarea class="lat-input lat-editor" id="spec" name="spec" rows="16" data-lat-grow="off">{{ spec }}</textarea>
</div>
shell.page_with(PageHead::new("Specification").assets(laterite_admin::CODE_EDITOR_ASSETS), body)
AttributeValuesDefault
data-languagetext, html, css, javascript, json, yaml, markdown, jinjatext
data-line-numbersoffon
data-wraponoff
--rowslines12
readonly on the textareaA read-only editor

Without the script the textarea is the control.

Choose from the library

var picker = lat.mediaPicker({
  multiple: false,
  words: { title: 'Choose from the library', use: 'Use selected', cancel: 'Cancel' },
  onDone: function (items) { console.log(items[0].id, items[0].url); }
});
picker.open('/admin/media/pick?mode=image');
OptionValues
multipletrue, false
wordstitle, use, cancel
onDone(items)each item: id, name, kind, thumb, url, is_image
open(url)the picker fragment, with ?mode=image for images alone

Write an island

window.lat.widget('char-count', function (el) {
  var input = el.querySelector('input');
  function count() { return input.value.length; }
  input.addEventListener('input', function () {
    el.querySelector('.count').textContent = count();
    lat.emit(el, 'acme.char-count:changed', { count: count() });
  });
  // Returned: `lat.get(el).count()` reads it from outside.
  return { count: count };
});
<div data-lat-widget="char-count">
  <input type="text" name="title">
  <span class="count">0</span>
</div>
ReturnDoes
The controller objectWhat lat.get(el) hands out.
rootThe markup an island built around its element; lat.get then finds the controller from inside it too.

Bind by structure, not by id: the same markup may appear more than once on a page and inside swapped content.

Testing

How a test drives a contributed route without a running server.

Test a route

let ctx = RouteCtx::builder(db)
    .admin_path("/backoffice")
    .base_url("https://acme.example")
    .build();

let response = Robots.mount(&ctx)
    .oneshot(Request::get("/").body(Body::empty())?)
    .await?;
BuilderDefault
base_path(..)/, where the screen mounted.
admin_path(..)/admin, where the panel mounted.
base_url(..)http://localhost, the site’s origin.
contributions(registry)Empty: what ctx.contributions reads.
events(events)A bus nothing listens on.
auth(service)A default service over the same database.

Every builder field has a default; name only what you assert on.

Migrations

A migration is a unit with a stable name, an up and an optional down; a module lists its migrations in apply order.

Write a migration

use laterite_core::strata::*;

One import brings the Migration trait, async_trait, the schema and query builders, Db, and the column helpers. lat make:migration <description> writes a new file with it.

One migration per file under src/migrations/, named m<NNNN>_<description>.rs, declaring pub struct Migration with a stable name, an up and an optional down. mod.rs lists them in apply order:

laterite_core::migration_set! {
    module_id: "acme.blog",
    m0001_create_posts,
    m0002_create_comments,
}

Append at the end. Never reorder or rename a shipped entry: applied migrations are tracked by (module_id, name).

Use the column helpers

use laterite_core::{bool_col, key_col};

Table::create()
    .table(Article::Table)
    .col(key_col(Article::Slug).not_null().unique_key())
    .col(bool_col(Article::Published).not_null().default(0));
HelperDescription
key_col(name)A key column: any id, code, token or column named in an index or foreign key. Chain .not_null(), .primary_key(), .unique_key() as usual. Use .text() only for unindexed prose.
bool_col(name)A boolean column. Bind and read it as a bool through the query helpers. Chain .not_null(), .default(0) as usual.

Ids are bigint auto-increment; an insert never sets one. Keep a migration to one schema change.

Queries

A query is built with the query builder and bound onto the pool through the portable helpers; the same code runs on Postgres, MySQL and SQLite.

Write a query

use laterite_core::strata::*;

let stmt = Query::select()
    .column(Article::Title)
    .from(Article::Table)
    .and_where(Expr::col(Article::Published).eq(true))
    .to_owned();
let (sql, values) = build(db.backend, &stmt);
let rows = bind_values(sqlx::query(&sql), values).fetch_all(&db.pool).await?;

Never hand-write SQL with ? placeholders. db is a laterite_core::Db: the pool paired with its backend.

HelperDescription
build(backend, &stmt)Renders a statement to (sql, values) for the backend.
bind_values(query, values)Binds the values onto a query, in order. A bool binds as a bool.
bind_values_as(query_as, values)The same, for a query_as mapping rows into a type.
insert_returning_id(db, stmt, id_column)Runs an insert and returns the new auto-increment id.
insert_returning_id_on(backend, conn, stmt, id_column)The same, on a connection inside a transaction.
on_conflict_ignore(keys)An insert’s conflict clause that ignores a duplicate of keys.
text_cast(backend)The type name to cast a column to a string: Expr::col(c).cast_as(Alias::new(text_cast(db.backend))).

Insert a row

let stmt = Query::insert()
    .into_table(Article::Table)
    .columns([Article::Title, Article::Published])
    .values_panic(["Hello".into(), true.into()])
    .to_owned();
let id = insert_returning_id(&db, stmt, Article::Id).await?;

Read a row

use laterite_core::AnyRowExt;

let published: bool = row.get_bool("published")?;
let title: String = row.get_text("title")?;
let summary: Option<String> = row.get_text_opt("summary")?;
let views: i64 = row.get_int("views")?;
AnyRowExtDescription
get_bool(column)A boolean.
get_text(column), get_text_opt(column)A string, or a nullable one. Never try_get::<String>.
get_int(column), get_int_opt(column)An integer of any declared width as i64, or a nullable one.

Models

A model is a struct over one table. #[derive(Model)] reads and writes it through laterite_core::model.

Generate one

lat make:model article --field title:text,views:integer,published_at:datetime
// src/models/article.rs
use laterite_core::model::{DateTime, Utc};

#[derive(Debug, Clone, laterite_core::Model)]
#[model(table = "articles")]
pub struct Article {
    pub id: i64,
    pub title: String,
    pub views: i64,
    pub published_at: Option<DateTime<Utc>>,
}

Declare one

AttributeOnDoes
#[model(table = "articles")]The structThe table; required
#[model(id = "article_id")]The structThe id field; default id, an i64
#[model(column = "published_at")]A fieldThe column; default the field’s name
Field typeColumn
StringText; null reads as empty
i64, i32Integer
boolbool_col
f64Floating point
DateTime<Utc>UTC text
serde_json::ValueJSON as text
Option<T>Any of the above, nullable

Read and write

use laterite_core::model;

let id = model::insert(&db, &Article { id: 0, title: "Hello".into(), views: 0, published_at: None }).await?;
let mut article = model::find::<Article>(&db, id).await?.expect("just inserted");
article.views += 1;
model::update(&db, &article).await?;
let every = model::all::<Article>(&db).await?;
FunctionReturns
find::<M>(db, id)Option<M>
all::<M>(db)Every row, in id order
find_many::<M>(db, &ids)HashMap<i64, M>, one query
insert(db, &model)The new id; the model’s own id is ignored
update(db, &model)Writes every column to the row with the model’s id

Load relations for a page

let ids: Vec<i64> = articles.iter().map(Model::id).collect();
let comments = model::has_many::<Comment>(&db, "article_id", &ids, |c| c.article_id).await?;
let authors = model::find_many::<Author>(&db, &author_ids).await?;

Each call is one query for the whole page: has_many groups the rows by their parent id, find_many keys them by id.

Seeding

A seeder puts a module’s data in the database: reference rows, defaults, demo content. It runs when asked, as often as asked.

Write a seeder

use laterite_core::seed::{insert_missing, Seeder, SeederSet};
use laterite_core::{CoreResult, Db, Record};

struct Statuses;

#[laterite_core::strata::async_trait]
impl Seeder for Statuses {
    fn name(&self) -> &str {
        "statuses"
    }

    async fn run(&self, db: &Db) -> CoreResult<()> {
        for (code, label) in [("draft", "Draft"), ("live", "Live")] {
            let mut rec = Record::new("acme_statuses");
            rec.set("code", code).set("label", label);
            insert_missing(db, &rec, &["code"]).await?;
        }
        Ok(())
    }
}

insert_missing(db, &rec, &key) inserts the row only when no row holds the same values in every key column, and returns whether it inserted. A second run changes nothing.

Register it

impl Module for BlogModule {
    fn seeders(&self) -> SeederSet {
        SeederSet::new("acme.blog", vec![Box::new(Statuses)])
    }
}

Run seeders

lat seed
lat seed acme.blog
CommandRuns
lat seedEvery loaded module’s seeders, in load order
lat seed <module>One module’s seeders
cargo run -- seed [module]The same, from the application binary

Each seeder that ran prints Seeded <module>/<name>.

Model Listeners

A listener runs when a record is written: fill a column, refuse a save, react to a change. It reaches every entity written through the save pipeline.

Build a record

let mut rec = Record::new("articles");
rec.set("title", "Hello")
   .set("views", 0i64)
   .set("published", true)
   .set("published_at", Utc::now());

rec.text("title");               // Some("Hello")
rec.int("views");                // Some(0)
rec.deserialize::<Article>()?;   // a struct view; extra attributes ignored

An absent attribute is not part of the write; a null one writes NULL.

Write a listener

use laterite_core::{ErrorBag, ModelListener, Op, Record, SaveCx, t};

struct Slugify;

#[laterite_core::strata::async_trait]
impl ModelListener for Slugify {
    async fn before_save(
        &self,
        cx: &mut SaveCx<'_>,
        rec: &mut Record,
        op: Op,
    ) -> Result<(), ErrorBag> {
        let Some(title) = rec.text("title") else {
            return Ok(());
        };
        if title.is_empty() {
            let mut bag = ErrorBag::default();
            bag.add("title", t!("A title is required."));
            return Err(bag);
        }
        rec.set("slug", slugify(title));
        Ok(())
    }
}
HookRunsReturn
before_saveInside the transactionErr(ErrorBag) refuses and rolls back; the user sees the messages on their fields.
after_saveAfter commitSide effects. Cannot roll back.
before_deleteInside the transactionErr(Text) refuses and rolls back.
after_deleteAfter commitSide effects.

All optional.

Register it

fn register(&self, registry: &mut Registry) {
    registry.add(ModelListenerReg::for_entity("articles", Arc::new(Slugify)));
    registry.add(ModelListenerReg::all(Arc::new(AuditWriter)));
}
RegistrationTargets
ModelListenerReg::for_entity(entity, listener)Records of one entity.
ModelListenerReg::all(listener)Every entity. Must not assume a column exists.

Read what changed

if rec.has_original() && rec.changed("title") {
    let was = rec.original("title").and_then(AttrValue::as_str);
}

changed is false without a snapshot; check has_original first.

Read the actor

match cx.actor() {
    Actor::User { id, username } => rec.set("updated_by", *id),
    Actor::System { process } => { /* a seeder, a job, the CLI */ }
    _ => {}
}

Stamp timestamps

FormConfig { timestamps: true, .. }
form:
  timestamps: true

Sets created_at on create and updated_at on every write; a created_at already on the record is kept. Opt in per form: a column added to every entity reaches tables without it.

Record who changed a row

form:
  footprints: true
FormConfig::new("posts", t!("Post"), "/admin/posts", "id", fields).footprints()
ColumnSet onValue
created_user_idCreateThe signed-in user’s id; null for a system write
updated_user_idEvery writeThe signed-in user’s id; null for a system write

A value already on the record is kept.

Generate a slug

form:
  slugs:
    slug: title
    handle: [first_name, last_name]
form.slug("slug", &["title"])
CaseResult
The slug is emptyBuilt from the sources: Hello World becomes hello-world, then hello-world-2, hello-world-3
The slug was typed and is freeStored slugged: Hello There becomes hello-there
The slug was typed and another row holds itRefused on the slug field
An edit keeps the stored slugStored unchanged

A slug is at most 180 characters, suffix included. Trashed rows hold their slug.

Seal a column

form:
  encrypt: [api_key]
form.encrypt(&["api_key"]);
let plain = rec.opened(&crypt, "api_key");
Value writtenResult
Plaintext, through the form or an importSealed under the application key
Null or emptyKept
Already sealed, such as from a sensitive fieldKept

Record::opened returns the plaintext, or None when the value does not open.

Guard a delete

#[laterite_core::strata::async_trait]
impl ModelListener for Guard {
    async fn before_delete(&self, cx: &mut SaveCx<'_>, rec: &Record) -> Result<(), Text> {
        Err(laterite_core::t!("Three records still reference this one."))
    }
}

Deletion is not an Op: a save listener never receives deletes. A persister refuses deletion unless it overrides delete.

Persisters

A persister replaces the generic insert and update for one entity.

Write a persister

#[async_trait]
impl Persister for NodePersister {
    async fn create(&self, cx: &mut SaveCx<'_>, rec: &Record) -> Result<i64, SaveError>;
    async fn update(&self, cx: &mut SaveCx<'_>, id: &str, rec: &Record) -> Result<(), SaveError>;
    async fn load(&self, cx: &mut SaveCx<'_>, id: &str) -> Result<Option<Record>, SaveError>;
    async fn delete(&self, cx: &mut SaveCx<'_>, id: &str, rec: &Record) -> Result<(), DeleteError>;
}
MethodDefault
createRequired.
updateRequired.
loadNone. The pre-write row, for listeners.
deleteRefuses.

cx carries the open transaction. Run every statement on it; never open your own.

Register it

registry.add_persister(PersisterReg::new("acme.tree", Arc::new(NodePersister)));

FormConfig::new("tree_node", "Node", "/nodes", "id", fields)
    .persist("acme.tree")
# descriptors/nodes.yaml
form:
  persist: acme.tree

Soft Delete

Delete moves a record to the trash. A trashed record leaves every list, form and export until it is restored or deleted permanently.

Add the column

use laterite_core::strata::*;

Table::create()
    .table(Alias::new("notes"))
    .col(ColumnDef::new(Alias::new("id")).big_integer().not_null().auto_increment().primary_key())
    .col(ColumnDef::new(Alias::new("title")).text().not_null())
    .col(soft_delete_col())
    .to_owned()

soft_delete_col() is a nullable deleted_at column.

Turn it on

entity: notes
path: /notes
title: Notes
permission: acme.manage_notes
soft_delete: true
list:
  deletable: true
  columns:
    title: {}
Resource::new("/notes", t!("Notes"), list).soft_delete()

The list

ViewButtonsRoute
The listDelete moves the selection to the trash; Trash opens the trashPOST {path}/delete
The trash (?trashed=1)Restore; Delete permanently; Leave the trashPOST {path}/restore, POST {path}/purge

A trashed record has no edit page. Delete permanently removes only records that are in the trash.

A trash and a restore are saves: model listeners, timestamps, footprints and the audit log see an update of deleted_at.

relations:
  comments:
    entity: comments
    foreign_key: note_id
    soft_delete: true
    list:
      columns:
        body: {}
    form:
      fields:
        body: {}
EventRelated rows
The parent is trashedEach live row takes the parent’s deleted_at value
The parent is restoredRows carrying that same value are restored; a row trashed on its own stays in the trash

The related table needs soft_delete_col() too. The section’s own Delete removes a row permanently.

Leave trashed rows out of a picker

TableSource::new("notes", "id", "title").scope(Arc::new(SoftDelete))

A search skips trashed rows; a stored id still shows its label.

Query Hooks

A query hook adds conditions to every admin read of an entity: list rows and their count, the edit form, export and relation sections.

Write a hook

use laterite_core::{QueryHook, ScopeCx};
use sea_query::{Alias, Expr, SelectStatement};

struct Published;

impl QueryHook for Published {
    fn name(&self) -> &str {
        "acme.published"
    }

    fn apply(&self, cx: &ScopeCx<'_>, select: &mut SelectStatement) {
        select.and_where(Expr::col((Alias::new(cx.entity), Alias::new("published"))).eq(1));
    }
}

Register it

Contributions {
    query_hooks: vec![
        QueryHookReg::for_entity("posts", Arc::new(Published)),
        QueryHookReg::all(Arc::new(TenantOnly)),
    ],
    ..Default::default()
}
ConstructorApplies to
QueryHookReg::for_entity(entity, hook)One entity
QueryHookReg::all(hook)Every entity a screen reads

A record a hook hides has no edit page.

Apply hooks in your own query

let mut select = Query::select();
select.column(Alias::new("id")).from(Alias::new("posts"));
laterite_core::scope::apply(&hooks, &ScopeCx::new("posts", db.backend), &mut select, &[]);

The last argument lists hook names to leave out, such as SoftDelete::NAME.

Built-in hooks

HookNameCondition
SoftDeletesoft_deletedeleted_at IS NULL; added by soft_delete

Records in Files

A resource’s source keeps its records as files: one file per record in a folder of the project, read into the table when the application starts and written back on every save.

# descriptors/posts.yaml
entity: posts
path: /posts
title: Posts
permission: acme.blog.manage_posts
source:
  kind: git
  path: content/posts
  format: markdown
  key: slug
  body: body
  slug_from: title
list:
  creatable: true
  deletable: true
  columns:
    title: { searchable: true }
form:
  title: Post
  fields:
    slug: {}
    title: { rules: [required] }
    pinned: { type: switch }
    body: { type: textarea, rows: 12 }
OptionDescription
pathThe folder, relative to the project root. Required.
kindfiles writes the file; git also commits it; or the code of a source a module registered. Default files.
formatyaml, json, or markdown (YAML front matter and a body). Default yaml.
keyThe text field that names the file. Default slug.
bodyWith markdown, the field the body under the front matter holds. Optional.
slug_fromA field the key is derived from when a save leaves it blank. Optional.

Scaffold it

lat make:resource article --field title:text --source content/articles --format markdown --git
FlagDescription
--source <DIR>The folder; a slug column names each file.
--formatyaml, json or markdown; markdown adds a body column. Default yaml.
--gitCommit every save.

Declare it from Rust

use laterite_admin::Resource;
use laterite_core::source::{Format, Source};

let posts = Resource::new("/posts", "Posts", list)
    .form(form)
    .permission("acme.blog.manage_posts")
    .source(
        Source::git("content/posts", Format::Markdown)
            .body("body")
            .slug_from("title"),
    );
ConstructorSource
Source::files(path, format)The folder, written.
Source::git(path, format)The folder, written and committed.
.body(column), .slug_from(column)The options above.

Write a file

<!-- content/posts/hello.md -->
---
title: Hello
pinned: true
---
# Hello

The first post.
FormatFileHolds
yamlhello.yamlThe form’s fields as a YAML document.
jsonhello.jsonThe form’s fields as a JSON object.
markdownhello.mdThe fields as front matter, the body field under it.

The file’s name is the key field: letters, digits, dots, dashes and underscores. The fields are written in the form’s order. A switch is true or false, a number input is a number, a repeater is a list, anything else is text.

Starting the application reads the folder: a file’s record is created or updated by key, and a record whose file is gone is removed. A file naming a field the form does not have fails the start, naming the file and the field.

Fit the table

Table::create()
    .table(Alias::new("posts"))
    .col(ColumnDef::new(Alias::new("id")).big_integer().not_null().auto_increment().primary_key())
    .col(ColumnDef::new(Alias::new("slug")).text().not_null())
    .col(ColumnDef::new(Alias::new("title")).text().not_null())
    .col(bool_col(Alias::new("pinned")).null())
    .col(ColumnDef::new(Alias::new("body")).text().null())
    .to_owned()
ColumnRule
The key fieldA text column; the form’s unique rule keeps one file per key.
A form fieldAny column type the field stores.
A column the form does not haveNeeds a default, or null.

Commit every save

source:
  kind: git
  path: content/posts
ActionCommit
CreateAdded content/posts/hello.md (ana)
EditUpdated content/posts/hello.md (ana)
Rename the keyThe old file is removed in the same commit.
DeleteRemoved content/posts/hello.md (ana)

The repository is the project root; git is on the path with a user name and email configured. Push the branch to publish: a host that builds on push rebuilds the site.

git push origin main

Build a page per record

use laterite_web::theme::build::{PathsReg, TableKeys};

registry.add(PathsReg::new(
    "/posts/:slug",
    Arc::new(TableKeys::new("posts", "slug")),
));
# pages/post.htm
url: /posts/:slug
components:
  post: { component: "acme.posts", slug: "{{ :slug }}" }
NameGives
PathsReg::new(pattern, paths)The pattern’s pages: the build renders it once per set of parameters paths answers.
TableKeys::new(table, column)One set per value of column, under the parameter of that name; .param(name) renames it.
PathsA trait for any other answer: async fn params(&self, db) -> Vec<Params>.

lat make:resource --source writes a src/site/<entity>.rs with the component and the PathsReg for /<table>/:slug, registered from the module. A pattern no module answers for is skipped by the build.

Register a source

use laterite_core::source::{PullReport, Pushed, RecordSource, RecordSourceReg, SourceCx, SourceError};

pub struct Sheets;

#[async_trait]
impl RecordSource for Sheets {
    async fn pull(&self, cx: &SourceCx<'_>) -> Result<PullReport, SourceError> {
        let sheet = cx.source.options["sheet"].as_str().unwrap_or_default();
        todo!("read {sheet} into {}", cx.entity)
    }
    async fn push(&self, cx: &SourceCx<'_>, pushed: &Pushed) -> Result<(), SourceError> {
        let row = cx.row(pushed.id).await?;
        todo!("write {row:?}")
    }
    async fn remove(&self, cx: &SourceCx<'_>, key: &str) -> Result<(), SourceError> {
        todo!("remove {key} from {}", cx.source.path)
    }
}

registry.add(RecordSourceReg::new("acme.sheets", Arc::new(Sheets)));
source:
  kind: acme.sheets
  path: content/guests
  sheet: Guests
MethodCalled
pullWhen the application starts. Creates or updates each row by key and removes the rest.
pushAfter a save commits, with the row’s id, the operation, and the key before a rename.
removeAfter a delete commits, with the row’s key.

cx.row(id) gives the row as the key, the columns by shape, and the body; cx.source.options holds the keys beyond the ones above; cx.actor names who is writing.

Portability

Laterite runs on Postgres, MySQL or SQLite, chosen by the connection URL; migrations and queries are written once.

Use portable types

You writeHelper
boolbool_col in schema; binds as bool; read with AnyRowExt::get_bool
DateTime<Utc>Convert to and from RFC 3339 text at the query boundary
JSON object or arrayserde_json to and from text at the boundary; no in-database JSON operators
Key, id or code columnkey_col; .text() only for unindexed prose
Any string readAnyRowExt::get_text, get_text_opt; never try_get::<String>
Any integer readAnyRowExt::get_int, get_int_opt
Unsigned integerAutomatic
New row idquery::insert_returning_id
Cast to stringExpr::col(c).cast_as(Alias::new(text_cast(db.backend)))
Insert, ignoring a duplicatequery::on_conflict_ignore(keys)
use laterite_core::{bool_col, AnyRowExt};

Table::create()
    .table(Article::Table)
    .col(bool_col(Article::Published).not_null().default(0));

let published: bool = row.get_bool("published")?;
let title: String = row.get_text("title")?;

Ids are bigint auto-increment; an insert never sets one. Canonicalise a user-facing unique key, lower-cased and trimmed, on write and on lookup.

Mind the differences the helpers do not hide

BackendRule
SQLiteForeign keys are enforced with PRAGMA foreign_keys = ON, set for you. Do not disable it.
MySQLUse key_col or .text() for every string column. Keep a migration to one schema change.
MySQLA unique key compares case-insensitively.

Events

An event is a fact a module announces; a listener acts on it. A listener cannot refuse an action, listen by a wildcard name, or be queued.

Listen

use laterite_auth::events::SignedIn;
use laterite_core::{EventCx, EventError, Listener, Registry};

struct WelcomeBack;

#[laterite_core::strata::async_trait]
impl Listener<SignedIn> for WelcomeBack {
    async fn handle(&self, cx: &EventCx<'_>, event: &SignedIn) -> Result<(), EventError> {
        acme::greetings::record(cx.db(), event.user_id).await?;
        Ok(())
    }
}

fn register(&self, registry: &mut Registry) {
    registry.listen::<SignedIn>(WelcomeBack);
}
In a listenerIs
eventThe payload, typed.
cx.db()The application’s pool.
cx.events()The bus, for announcing a fact of the listener’s own.
Err(..)Logged with the event and the listening module. The listeners after it still run, and the announcer is not told.

Announce

use laterite_core::Event;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
#[non_exhaustive]
pub struct Published {
    pub article_id: i64,
}

impl Published {
    pub fn new(article_id: i64) -> Self {
        Self { article_id }
    }
}

impl Event for Published {
    const NAME: &'static str = "acme.blog.published";
}
impl Screen for Articles {
    fn mount(&self, ctx: &RouteCtx) -> Router {
        let events = ctx.events().clone();
        let list = ctx.url("/");
        Router::new().route("/{id}/publish", post(move |Path(id): Path<i64>| {
            let (events, list) = (events.clone(), list.clone());
            async move {
                // ... write and commit, then:
                events.emit(&Published::new(id)).await;
                Redirect::to(&list)
            }
        }))
    }
}
PartRule
NAMEThe module’s id, then the fact in the past tense: acme.blog.published. Two types under one name stop the start, naming both.
PayloadSerde in both directions. #[non_exhaustive] with a constructor.
MomentAfter the write has committed.
WhereThe bus
A screen or a public routectx.events() on RouteCtx
Routes added with Bootstrap::extendctx.events() on BootstrapCtx
A listenercx.events()
Beside an AuthServiceauth.events()

Listen for a framework event

Types are in laterite_auth::events.

NameTypeFields
auth.signed_inSignedInuser_id, username, ip_address, user_agent
auth.sign_in_failedSignInFaileduser_id (none for an unknown username), username, ip_address, user_agent
auth.locked_outLockedOutuser_id, username, ip_address, user_agent
auth.signed_outSignedOutuser_id
auth.password_changedPasswordChangeduser_id, changed_by (none for a process); by_owner()

Record writes are heard through Model Listeners, which can also refuse one.

Test a listener

let events = Events::builder(db.clone())
    .listen::<SignedIn>(WelcomeBack)
    .build()?;

// A listener, alone.
events.emit(&SignedIn::new(7, "ada", &RequestContext::default())).await;

// The service announcing to it.
let auth = AuthService::new(db.clone(), AuthConfig::default()).with_events(events.clone());

// A route announcing to it.
let ctx = RouteCtx::builder(db).events(events).build();
let response = Articles.mount(&ctx).oneshot(request).await?;

Sessions and CSRF

A session cookie signs an operator in. Alongside the identity it carries a CSRF token, flash messages and a data blob.

Send the CSRF token

Every POST, PUT, PATCH and DELETE on the admin mount carries the session’s token, in the _csrf field or the X-CSRF-Token header. Descriptor forms and htmx requests carry it already. A hand-written form includes it:

<form method="post" action="{{ action }}">
  {% include "_csrf.html" %}
  ...
</form>

A scripted request sends the header; a template exposes the token as shell.csrf_token:

<button type="button" data-acme-publish data-csrf="{{ shell.csrf_token }}">Publish</button>
document.addEventListener('click', function (e) {
  var button = e.target.closest('[data-acme-publish]');
  if (!button) return;
  fetch(button.dataset.action, {
    method: 'POST',
    credentials: 'same-origin',
    headers: { 'X-CSRF-Token': button.dataset.csrf }
  });
});

A request without the token renders a 403 “Request blocked” page. Login and first-run setup have no session and need no token.

Read an upload

use laterite_admin::VerifiedUpload;

async fn import(mut upload: VerifiedUpload) -> Result<Response, AdminError> {
    while let Some(field) = upload.next_field().await? {
        // ... stream the field ...
    }
    Ok(Redirect::to("/admin/import").into_response())
}

An upload’s form puts the token in its first field; VerifiedUpload checks it while reading and offers the remaining fields as Multipart does. Take an upload with it, never with a bare multipart parser.

Load scripts as assets

Every admin response carries these; a handler that sets one of its own keeps its value. Inline scripts and handlers are refused: a screen binds its behaviour from a script file and a data- attribute.

HeaderValue
Content-Security-PolicyScripts and fonts from the admin’s own assets; inline styles allowed; images and media also from https:
X-Content-Type-Optionsnosniff
X-Frame-OptionsSAMEORIGIN
Referrer-Policysame-origin
Permissions-Policycamera=(), microphone=(), geolocation=(), payment=()
Cross-Origin-Opener-Policysame-origin
Strict-Transport-Securitymax-age=31536000; includeSubDomains, with secure_cookie = true
<button type="button" data-acme-refresh>Refresh</button>
document.addEventListener('click', function (e) {
  if (e.target.closest('[data-acme-refresh]')) location.reload();
});

Flash a message

use laterite_admin::{FlashLevel, SessionHandle};
use laterite_core::t;

async fn save(Extension(session): Extension<SessionHandle>, /* ... */) -> Response {
    // ... persist ...
    session.push_flash(FlashLevel::Success, t!("Settings saved."));
    Redirect::to("/admin/settings").into_response()
}
CallDescription
push_flash(level, text)Shown on the next full page, across a redirect, then cleared.
push_flash_sticky(level, text)Shown until dismissed.
FlashLevelSuccess, Error, Info.

Change a password

use laterite_core::Actor;

auth.change_password(
    user.id,
    &new_password,
    Some(&session_token),
    &Actor::user(user.id, &user.username),
)
.await?;
ArgumentValue
user_idThe account whose password changes.
new_passwordRefused under password_policy.min_length (default 8).
keep_tokenThe session to keep signed in, or None to end all of them.
actorWho made the change, recorded on the audit log. Actor::system("lat admin reset-password") for a process.

AuthService::password_changed_at(user_id) returns when it last changed, or None if never recorded.

An operator’s own change, from Preferences → Password, goes through:

auth.change_own_password(user.id, &current, &new_password, &session_token, &ctx)
    .await?;
ErrorReturned when
AuthError::InvalidCredentialscurrent does not match. Counts as a failed sign-in.
AuthError::TooManyAttemptsThe account is locked out.
AuthError::RefusedThe new password is under password_policy.min_length.

A change through this call is also on the access log as password_changed.

A password made for an operator is temporary:

auth.require_password_change(user.id).await?;

Every admin request then redirects to Preferences → Password until the operator sets their own. lat admin create --generate and lat admin reset-password --generate mark the account the same way.

Purge expired sessions

Expired sessions and stay-signed-in credentials are removed for you, and on demand:

lat admin purge
let purged = auth.purge_expired().await?;
println!(
    "{} sessions, {} credentials, {} access log rows",
    purged.sessions, purged.remember_tokens, purged.access_log
);

Access log rows older than access_log_retention_days go in the same sweep.

Sign out

auth.logout_with(&session_token, &ctx).await?;

The sign-out is on the access log as logout, from the address and client in ctx. auth.logout(&session_token) records it with neither.

Handle an expired session

Every guarded response carries when the session ends, and a page asks for it on demand:

X-Lat-Session-Ends: 1761307200
GET /admin/session
{"ends":1761307200}

POST /admin/session, with the request token, renews the session to its full idle window and answers the same way.

A request past the deadline is answered by the kind of request it was:

RequestAnswer
PageA redirect to the login page with ?ended=expired.
htmx401 with HX-Trigger: lat:session-expired; the admin page signs in again in place and retries the request.
Scripted (X-Requested-With: fetch)401.

A scripted sign-in posts the login form with X-Requested-With: fetch and gets JSON back:

POST /admin/login
X-Requested-With: fetch

username=ada&password=...
{"ok": true, "csrf": "<the new request token>", "ends": 1761314400}
{"ok": false, "error": "Invalid username or password."}

A script of your own that posts after a re-login reads the token from the _csrf field of any rendered form, or from the hx-headers attribute on body; both are updated.

The page’s dialog and warning announce lat:session:expired and lat:session:renewed on #lat-session.

Read the sign-out notice

A redirect to the login screen carries ?ended=<code> when the session was ended for a reason the login page can show; an htmx request gets HX-Redirect with no body, except for expired (see above).

CodeShown when
expiredInactivity, or the session’s ceiling.
password_changedAuthService::change_password ended every other session.
deactivatedThe account was deactivated.
signed_out_elsewhereOne device, or every other device, was signed out.

Localization

English strings in code and templates are the catalog keys. A .po file per language translates them.

Write translatable text

use laterite_core::{t, tn};

let msg = t!("Your changes were saved.");
let greeting = t!("Welcome back, {name}.").arg("name", user.name.clone());
let label = tn!("{n} item", "{n} items", count).arg("n", count);
WhereCall
Rustt!("..."); tn!("one", "many", n) for plurals. Both build a Text, localized at render.
Templateshell.t("..."); shell.tf(...) with numeric placeholders.
Descriptor labelsAlready Text, localized where they render.

A placeholder such as {name} appears unchanged in every translation.

Manage catalogs

lang/
  messages.pot     # generated template, every source string
  de.po            # a German translation
lat i18n extract          # regenerate every messages.pot
lat i18n update de        # create or refresh de.po from the template
lat i18n status           # per-locale coverage
lat i18n check            # fail if any messages.pot is stale; run in CI

A translator fills in msgstr:

#: templates/login.html
msgid "Admin panel"
msgstr "Verwaltung"

Ship a language from a module

impl Module for AcmeModule {
    fn catalogs(&self) -> &'static [(&'static str, &'static str)] {
        &[
            ("de", include_str!("../lang/de.po")),
            ("fr", include_str!("../lang/fr.po")),
        ]
    }
}

A malformed catalog, or one whose placeholders differ from the source, fails the start.

Set the language

OrderSource
1The operator’s preference, from Preferences.
2The browser’s Accept-Language.
3backend.locale.
4English.

Only a language with a loaded catalog is offered or chosen. Month and day names follow a locale that carries a territory, de_DE.

Preview coverage

Set the locale to xx, or send Accept-Language: xx: every translated string renders bracketed and accented, [Ṡäṽé]. Plain text is a string that bypassed translation.

Search

A SearchProfile sets how a lookup folds a query and widens it before matching. A list’s search box folds case over its searchable columns and takes no profile.

Attach a profile to a picker source

use laterite_admin::picker::TableSource;
use laterite_core::search::{Numerals, SearchProfile};

let source = TableSource::new("acme_cities", "id", "name_folded")
    .with_search(SearchProfile::folding().with_expander(Numerals));

let profile = SearchProfile::folding();
assert_eq!(profile.fold("  Ávila's  Café "), "avilas cafe");
Constructor or methodDescription
SearchProfile::new()Folds case only, matched by substring. The default of every lookup.
SearchProfile::folding()Folds case, diacritics, punctuation and whitespace.
with_chain(chain)A NormalizerChain of your own.
with_expander(expander)Adds a way of widening the query; may repeat.
with_matcher(matcher)A matcher of your own, used when the database supports it.
fold(text)The folded form of text.
candidates(query)The folded query and its expansions.
NormalizerEffect
LowercaseCase.
DiacriticsAccents removed.
PunctuationRemoved.
WhitespaceCollapsed.

NormalizerChain::standard() applies all four in order; NormalizerChain::new().with(..) builds one by hand. A profile folds the query, not stored values: widen it only where the column holds folded values. NormalizerChain::fingerprint() names the chain, case+diacritics+punctuation+whitespace; keep it beside folded data and compare after a chain change.

list:
  search: { prompt: Search by title, on_enter: true }
  columns:
    title: { label: Title, searchable: true }
    body:  { label: Body, searchable: false }
OptionDescription
search.enabledfalse removes the box. On by default.
search.promptThe placeholder. “Search” when unset.
search.on_enterAsk on Enter only. Off by default: the list narrows as the operator types.
<column>.searchableWhether the box matches this column. Text columns are searchable by default; other types are not.

Add an alias

use laterite_core::search::{Aliases, SearchProfile};

let profile = SearchProfile::folding()
    .with_expander(Aliases::new().pair("bengaluru", "bangalore"));

Aliases::pair(a, b) makes each find the other. Fold alias values through the same chain before adding them.

Widen matching

use laterite_core::search::{NormalizerChain, Numerals, SearchProfile};

let profile = SearchProfile::new()
    .with_chain(NormalizerChain::standard())
    .with_expander(Numerals);
ExpanderEffect
NumeralsEnglish number words and digits, both ways, on whole tokens: 7 rivers finds seven rivers.
AliasesPairs that reach each other.

An expander widens the query alone; stored data is untouched.

Storage Disks

A disk holds files; a record points at one and your tables point at the record. The media table migrates with the admin; the crate is a dependency only for code that calls it.

[dependencies]
laterite-media = "0.12"
TermMeaning
BlobThe bytes of a file.
RecordA file with a stable id, pointing at a blob.
LinkAttaches a record to its owner.

Replacing a file makes a new blob; the record’s id and every reference to it stay.

Declare disks

let public = LocalDisk::new("storage/media").public_at("/storage/media");
let private = LocalDisk::new("storage/private");

fn register(&self, registry: &mut Registry) {
    registry.add(DiskReg::new("private", Arc::new(private)).label("Uploads kept out of the library"));
}
DiskServing
PublicFiles served directly at the path.
PrivateNo public URL; streamed through the application.

A module that stores files reads the disks through ctx.contributions::<DiskReg>() and picks one by name. The admin’s import keeps uploads on private: the registered disk of that name, else private under backend.storage. The library uploads to public, else media there.

Add an S3 disk

[dependencies]
laterite-media = { version = "0.12", features = ["s3"] }
use laterite_media::{DiskReg, S3Config, S3Disk};

let config: S3Config = settings.get("storage.disks.s3")?;
let disk = Arc::new(S3Disk::from_config(&config).await);
registry.add(DiskReg::new("s3", disk));
[storage.disks.s3]
bucket = "acme-media"
region = "auto"
endpoint = "https://<account>.r2.cloudflarestorage.com"
access_key = "..."
secret_key = "..."
prefix = "media"
public_url = "https://media.acme.test"
KeyDefaultMeaning
bucketThe bucket.
regionautoThe region name.
endpointAWSThe store’s URL (R2, MinIO, B2, Spaces, Wasabi).
access_key, secret_keythe SDK’s default chainStatic credentials.
prefix""A key prefix every blob goes under.
public_urlnoneThe origin blobs are reachable at unsigned; unset, the disk is private and serves through presigned URLs.
path_styletrue with an endpointendpoint/bucket/key addressing.

signed_url presigns a GET, presigned_put a PUT for a direct upload, and copy is server-side.

Take a file in

use laterite_media::{ingest, LocalDisk};

let disk = LocalDisk::new("storage/private");
let stored = ingest(&disk, stream, 10 * 1024 * 1024).await?;

let id = laterite_media::record::create(&db, NewMedia {
    disk: "private".into(),
    hash: stored.hash,
    size: stored.size as i64,
    content_type: stored.content_type,
    original_name: filename,
    in_library: false,
    created_by: Some(user.id),
}).await?;

ingest(disk, stream, limit) takes any byte stream: a browser upload, a server-side fetch, a URL import. It aborts and discards past the limit, and sniffs the content type from the bytes.

Receive an upload

async fn receive(mut upload: VerifiedUpload) -> impl IntoResponse {
    while let Some(field) = upload.next_field().await? {
        // the token field is already consumed and checked
    }
}
<form method="post" action="{{ action }}" enctype="multipart/form-data">
  <input type="hidden" name="_csrf" value="{{ shell.csrf_token() }}">
  {% let upload_id = "file" %}
  {% let upload_accept = ".csv" %}
  {% let upload_multiple = false %}
  {% let upload_url = String::new() %}
  {% let upload_fields = String::new() %}
  {% let upload_direct = String::new() %}
  {% let upload_hint = shell.t("A CSV file.") %}
  {% include "_upload.html" %}
  <button class="lat-btn lat-btn--primary" type="submit" data-upload-submit>{{ shell.t("Upload") }}</button>
</form>

_csrf comes first in the form, or arrives as the X-CSRF-Token header. A route that parses the upload without VerifiedUpload has its response refused.

VariableValue
upload_idThe input’s id, for its label.
upload_acceptAn accept list, or empty.
upload_multipletrue for several files.
upload_urlEmpty: the form submits the file. A URL: the zone posts each file there itself, with _csrf first and X-Requested-With: fetch, shows its progress, and reloads once every file is stored.
upload_fieldsFields sent before each file (folder=3;kind=image).
upload_directEmpty, or the URL of a direct upload route the zone tries first.
upload_hintA line under the prompt.
data-upload-submitOn the form’s button: hidden while the zone sends.

A route the zone posts to answers JSON:

{"stored": [{"id": 7, "name": "cover.png", "href": "/admin/media/7", "url": "/storage/media/<hash>/cover.png"}],
 "refused": [{"name": "huge.mov", "reason": "Larger than the upload limit."}]}
EventDetail
lat:upload:picked{count}, in a form.
lat:upload:before-send{count}, cancelable.
lat:upload:stored, lat:upload:failed{name, reason} per file.
lat:upload:done{failed} once every file answered.

Check what comes in

# config/default.toml
[backend]
upload_extensions = ["jpg", "jpeg", "png", "webp", "svg", "pdf", "css"]
use laterite_media::sanitize;

if !sanitize::extension_allowed(&name, ctx.upload_extensions()) {
    return refused(t!("This file type is not allowed."));
}
let bytes = match sanitize::svg(&bytes) {
    Some(drawing) => drawing.into_bytes(),
    None if sanitize::is_svg(&bytes) => return refused(t!("The image could not be read.")),
    None => bytes,
};
FunctionDoes
extension_allowed(name, list)The name’s extension, lowercased, is in the list. A name with none is refused.
is_svg(head)The leading bytes are an SVG document, past any prolog, comment or doctype.
svg(bytes)The SVG as a drawing: script, foreign content, event handlers, external references and javascript: URLs removed; style cleaned; the namespace present. None when it is not an SVG.
css(text)A stylesheet without imports, script URLs, expressions, bindings or a closing tag.
DEFAULT_EXTENSIONSThe list when upload_extensions is empty: images, documents, audio, video, fonts, archives.

The library’s own upload, direct upload and media field run these checks.

Serve a file

Every record serves at /storage/media/<hash>/<name>:

HeaderValue
ETagThe hash; If-None-Match answers 304.
Cache-Controlpublic, max-age=31536000, immutable
X-Content-Type-Optionsnosniff
Content-Dispositioninline, or attachment for SVG, HTML, script and any Other kind.

A record on a disk registered .private() serves only at a signed URL:

registry.add(DiskReg::new("vault", Arc::new(private)).private());
let url = laterite_admin::medialib::file_url(&record);
let timed = laterite_admin::medialib::signed_file_url(&ctx, &record, Duration::from_secs(3600));
// /storage/media/<hash>/<name>?e=<expiry>&t=<signature>
PartValue
eExpiry, seconds since the epoch.
tA signature over the hash and the expiry, made with backend.secret.
Cache-Controlprivate, no-store
Bare, expired, altered or retargeted404

Inside the admin a private file has an address of its own, with no signature:

/admin/media-files/<id>/<name>
/admin/media-files/<id>/<preset>/<name>
Who asksAnswer
Signed outThe sign-in page.
A superuserThe file.
Holds media.browse, and the file is in the libraryThe file.
Holds the permission of a resource or relation whose record the file is attached toThe file.
Anyone else404

Write a driver

#[async_trait]
impl StorageDriver for MyDisk {
    async fn put(&self, path: &str, data: ByteStream) -> Result<(), StorageError>;
    async fn get(&self, path: &str) -> Result<ByteStream, StorageError>;
    async fn delete(&self, path: &str) -> Result<(), StorageError>;
    async fn metadata(&self, path: &str) -> Result<Option<BlobMeta>, StorageError>;
    fn public_url(&self, path: &str) -> Option<String>;
    async fn signed_url(&self, path: &str, expires_in: Duration, disposition: Disposition)
        -> Result<Option<String>, StorageError>;
}

There is no list(). Write to a temporary path and move into place. signed_url defaults to None: the framework then streams the file itself behind its own token. A store that presigns returns the URL.

Encryption and Signing

The application key seals values at rest, signs links and mints tokens with an expiry; every operation names a purpose, and a value sealed for one purpose never opens under another.

lat key generate
# config/local.toml
[app]
key = "1:k8xq...="            # id:<base64 of 32 bytes>; or LAT__APP__KEY
previous_keys = ["0:u9Yr...="]   # keys retired by a rotation, still read
let crypt = ctx.crypt();
let sealed = crypt.encrypt("api-secret", b"integrations.token.42", b"hunter2")?;
let plain = crypt.decrypt("api-secret", b"integrations.token.42", &sealed)?;
let signature = crypt.sign("export-link", b"report:7");
let ok = crypt.verify("export-link", b"report:7", &signature);
let token = crypt.token("password-reset", b"user:7", Duration::from_secs(3600));
let payload = crypt.check_token("password-reset", &token)?;
let index = crypt.blind_index("pan", b"1234-5678");
MethodDoes
encrypt(purpose, aad, plain)Seals plain, bound to aad; base64url text with the key id inside.
decrypt(purpose, aad, sealed)Opens a value sealed under any key the application holds; CryptError::Invalid on a wrong purpose, AAD, key or tampering.
sign(purpose, message)A signature of message, base64url.
verify(purpose, message, signature)Constant-time check under any held key.
token(purpose, payload, ttl)A signed token carrying payload and an expiry.
check_token(purpose, token)The payload while the token lives; CryptError::Expired after.
blind_index(purpose, plain)A keyed digest to find a sealed value by equality.

aad names what the value belongs to (a table, column and row); a sealed value moved to another row does not open. ctx.sign and ctx.verify_signature on a route are sign and verify for the url purpose.

Set the key

KeyDescription
app.keyid:<base64> of 32 random bytes; lat key generate writes one into config/local.toml. Unset, a key derived from backend.secret or the key stored at the first start is used, and a production start logs a warning.
app.previous_keysKeys retired by a rotation, each id:<base64>, used for reading only.
CommandDoes
lat key generateWrites a new key as app.key. A key already set is replaced; add --rotate to keep it under previous_keys, or --print to print without writing.
lat key showThe id of the key in use and of the previous keys.

Seal a form field

fields:
  api_token: { type: sensitive }

The sensitive field stores its value sealed and reveals it on request, recorded in the audit log.

Rotate the key

lat key generate --rotate
lat crypt rotate       # re-seals stored values under the new key

lat crypt rotate re-seals every sensitive column under the key in use and reports what it re-sealed, what was already current and what did not open. Remove the old key from previous_keys once it reports nothing left to re-seal. Without an app.key, --rotate keeps the key derived from backend.secret as the previous key.

Test with a key of your own

let crypt = laterite_core::Crypt::ephemeral();
let ctx = RouteCtx::builder(db).build();   // builds on an ephemeral key

Cache

A value is kept under a key for a lifetime, together with the namespaces it was built from. A write bumps its namespace; every value built from that namespace misses from then on, in every process of the deployment.

use std::time::Duration;
use laterite_core::cache::records;

let menu: Vec<MenuItem> = ctx
    .cache()
    .remember(
        "acme.blog::menu",
        Duration::from_secs(3600),
        &[&records("posts"), "acme.blog::feed"],
        || async { load_menu(ctx.db()).await },
    )
    .await?;
MethodDoes
remember(key, ttl, deps, load)The value under key, or what load returns, stored for ttl as JSON and built from deps. Concurrent callers for one key share one load.
get(key)The bytes under key while every namespace in its deps stands where it stood; get_json::<T> decodes them.
put(key, bytes, deps, ttl)Stores bytes; put_json(key, &value, deps, ttl) stores a value as JSON.
add(key, bytes, deps, ttl)Stores only when nothing is under key; true when it did.
forget(key)Drops the value under key.
bump(namespace)Moves the namespace on; returns the new generation.
generation(namespace)The namespace’s generation.
lock(name, ttl)Some(lock) when no other holder has name; see below.
flush()Drops every value this process holds.

A namespace in deps is one registered below, or one of the record family records::<entity>. An unregistered one is refused with CoreError::Validation.

Configure the store

# config/default.toml
[cache]
store = "auto"            # auto | null | memory | redis
memory_mib = 64
poll_seconds = 2
# url = "redis://127.0.0.1:6379/0"
# prefix = "acme"
KeyDescription
cache.storeauto is null while app.debug is on and memory otherwise. Default auto.
cache.memory_mibThe memory store’s capacity. Default 64.
cache.poll_secondsHow often a process reads the generations the other processes bumped; 0 turns it off for a single process. Default 2.
cache.urlThe Redis URL for the redis store.
cache.prefixThe prefix of every Redis key. Default laterite.
[dependencies]
laterite-core = { version = "0.12", features = ["redis"] }
StoreValuesGenerations and locks
nullKept nowhereThe database
memoryThis processThe database
redisRedisRedis

Register a namespace

use laterite_core::cache::CacheNamespace;

fn register(&self, registry: &mut Registry) {
    registry.add(CacheNamespace::new("feed"));
}

The namespace is acme.blog::feed: the registering module’s id, two colons, the name.

NamespaceBumped by
records::<entity>Every save and delete of the entity through the admin or a FormHandle.
laterite.settings::valuesA save through ctx.settings().
laterite.parameters::valuesA write through ctx.parameters().
laterite.theme::templatesA theme write through Themes.

Write through the handles

ctx.settings().save(&BrandSetting { app_name: "Acme".into(), ..Default::default() }).await?;
ctx.parameters().set("acme.blog::sync.cursor", &cursor).await?;
Themes::of(ctx).save_template(theme.id, Kind::Page, "about.htm", None, markup, None).await?;
ctx.cache().bump("acme.blog::feed").await?;
HandleRaw function
ctx.settings().set / .savelaterite_admin::settings::set / save
ctx.parameters().set / .resetlaterite_core::parameters::set / reset
Themes::of(ctx).save_template and the other writeslaterite_web::theme::store::*

A raw function writes the table alone; the handle writes it and bumps.

Hold a lock

if let Some(lock) = ctx.cache().lock("acme.blog::sync", Duration::from_secs(300)).await? {
    sync(ctx.db()).await?;
    lock.release().await?;
}

A lock not released lapses when its lifetime passes.

Clear from the command line

lat cache clear                          # every namespace
lat cache clear --namespace records::posts
lat cache list

Queue

A job is a struct that implements Job; pushing it stores the struct as JSON, and a worker runs it with retries, a timeout and a failed list.

use laterite_core::queue::{Job, JobCx, JobError, QueueRegistry};
use laterite_core::strata::async_trait;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct SendDigest {
    user_id: i64,
}

#[async_trait]
impl Job for SendDigest {
    const NAME: &'static str = "acme.blog::send_digest";

    async fn run(&self, cx: &JobCx) -> Result<(), JobError> {
        digest::send(cx.db(), self.user_id).await?;
        Ok(())
    }
}

fn register(&self, registry: &mut Registry) {
    registry.add_job::<SendDigest>();
}
ctx.queue().push(&SendDigest { user_id: 7 }).await?;
ctx.queue().push_in(&SendDigest { user_id: 7 }, Duration::from_secs(600)).await?;
ctx.queue().push_at(&SendDigest { user_id: 7 }, tonight).await?;
MethodDoes
push(&job)Stores the job, due now. Pushed::Queued(id), Pushed::Ran in inline mode, Pushed::Duplicate when its unique key is already waiting.
push_in(&job, delay)Due after delay.
push_at(&job, when)Due at when.
counts()How many jobs wait and run on each queue.
failed()The failed list, newest first.
retry(id) / forget(id)Put a failed job back, or drop it; None for every one.
clear(queue)Drops the waiting jobs on one queue, or on all with None.

A job whose type is not registered is refused at push with CoreError::Validation.

Set the job’s rules

#[async_trait]
impl Job for SendDigest {
    const NAME: &'static str = "acme.blog::send_digest";
    async fn run(&self, cx: &JobCx) -> Result<(), JobError> { /* ... */ }

    fn queue(&self) -> String { "mail".into() }
    fn tries(&self) -> u32 { 5 }
    fn backoff(&self, attempt: u32) -> Duration { Duration::from_secs(30 * u64::from(attempt)) }
    fn timeout(&self) -> Option<Duration> { Some(Duration::from_secs(120)) }
    fn retry_until(&self) -> Option<DateTime<Utc>> { Some(Utc::now() + Duration::hours(6)) }
    fn unique_key(&self) -> Option<String> { Some(format!("digest:{}", self.user_id)) }
}
MethodDefaultMeaning
queue()defaultThe queue the job lands on.
tries()3Attempts before the job fails; 0 leaves it to retry_until.
backoff(attempt)10 s, doublingThe wait after attempt attempt failed.
timeout()60 sThe longest one attempt may run; None for no limit.
retry_until()NoneKeep retrying until this moment, whatever tries says.
unique_key()NoneA push while a job with this key waits or runs is dropped, scheduled pushes included.
ReturnEffect
Ok(())The job is removed.
Err(JobError::retry(message))Released for the next attempt after the backoff, or failed on the last one.
Err(JobError::fail(message))Failed at once, whatever tries remain.
Err(JobError::release(wait, reason))Back after wait on the same attempt: a rate limit or a Retry-After.
async fn run(&self, cx: &JobCx) -> Result<(), JobError> {
    let token = cx.crypt().and_then(|c| c.decrypt(FIELD_PURPOSE, b"api_token", &sealed).ok());
    match acme::api::fetch(token).await {
        Err(acme::api::Error::Limited { retry_after }) => Err(JobError::release(retry_after, "rate limited")),
        Err(e) => Err(JobError::retry(e)),
        Ok(page) => {
            cx.queue().push(&StorePage { page }).await?;
            Ok(())
        }
    }
}
MethodReturns
db(), events(), cache(), parameters()The application’s services.
queue()The queue, to push further jobs.
crypt()The application’s crypt, None on a queue built without one.
attempt()Which attempt this is, from 1.
queue_name()The queue the job was taken from.
id()The job’s row id, None inline.

Configure the queue

# config/default.toml
[queue]
store = "auto"            # auto | database | redis
mode = "worker"           # worker | external | inline
workers = 2
queues = ["default"]
retry_after_seconds = 90
poll_seconds = 1
# url = "redis://127.0.0.1:6379/0"
# prefix = "acme"
KeyDescription
queue.storeWhere jobs wait. auto is database; redis needs the redis feature of laterite-core and queue.url.
queue.urlThe Redis URL for the redis store.
queue.prefixThe prefix of every Redis key. Default laterite.
queue.modeworker runs the workers in the application process; external leaves them to queue work; inline runs a job as it is pushed.
queue.workersHow many workers the process runs in worker mode. Default 2.
queue.queuesThe queues a worker takes from, in priority order: a job waiting on an earlier queue is taken first. Default ["default"].
queue.retry_after_secondsAfter this long a claimed job counts as abandoned and is claimed again. Longer than any job’s timeout. Default 90.
queue.poll_secondsHow long an idle worker waits before looking again. Default 1.

Run a worker apart

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    Bootstrap::new("config")
        .module(migrations::AppModule)
        .run()
        .await
}
lat queue work                       # cargo run -- queue work
lat queue work --once
lat queue work --stop-when-empty --queue high,default
acme queue work                      # the built binary

Bootstrap::run reads the process’s arguments: serve (the default), queue work or schedule run. With queue.mode = "external", the serving process runs no worker.

Act on the failed list

lat queue list
lat queue failed
lat queue retry 42
lat queue retry all
lat queue forget 42
lat queue flush --queue mail
use laterite_core::queue::JobFailed;
use laterite_core::{EventCx, EventError, Listener};

struct Alert;

#[laterite_core::strata::async_trait]
impl Listener<JobFailed> for Alert {
    async fn handle(&self, cx: &EventCx<'_>, failed: &JobFailed) -> Result<(), EventError> {
        acme::alerts::record(cx.db(), &failed.name, &failed.error).await?;
        Ok(())
    }
}

fn register(&self, registry: &mut Registry) {
    registry.listen::<JobFailed>(Alert);
}

A job reaching the failed list announces queue.job_failed with its id, name, queue, attempts and error.

Grant the Jobs screen

# a role's permissions
- backend.manage_jobs
PermissionGrants
backend.manage_jobsSettings → System → Jobs: the waiting and running counts per queue, the failed list with each job’s payload and error, Retry and Forget for one job or all.

Test a job

let queue = Queue::inline(vec![JobReg::of::<SendDigest>()], services);
assert_eq!(queue.push(&SendDigest { user_id: 7 }).await?, Pushed::Ran);
# config/test.toml
[queue]
mode = "inline"

Scheduler

An entry names a cron expression and what to do; the application evaluates every entry each minute, in the entry’s timezone, on one process of the deployment.

use laterite_core::schedule::{Overlap, ScheduleEntry, ScheduleRegistry};

fn register(&self, registry: &mut Registry) {
    registry.add_schedule(
        ScheduleEntry::new("acme.blog::digest", "0 7 * * *")
            .timezone("Europe/Berlin")
            .description("Send the daily digest.")
            .job(SendDigest { user_id: 0 }),
    );
    registry.add_schedule(
        ScheduleEntry::every_minutes("acme.blog::sweep", 5)
            .run(|cx| async move { sweep(cx.db()).await }),
    );
}
ConstructorExpression
ScheduleEntry::new(name, expression)Five fields (0 7 * * *), six with seconds, or @hourly, @daily, @weekly, @monthly, @yearly.
ScheduleEntry::every_minutes(name, n)*/n * * * *
ScheduleEntry::hourly(name)0 * * * *
ScheduleEntry::daily_at(name, "07:30")30 7 * * *
MethodDefaultMeaning
.run(|cx| async { .. })Runs the closure when due; cx gives db(), events(), cache(), parameters(), queue().
.job(job)Pushes the job when due.
.timezone("Asia/Colombo")UTCThe timezone the expression is read in.
.description("..")A line for the Scheduled tasks screen.
.overlap(Overlap::Allow)Overlap::SkipWhether a due entry runs while its last run is still going.
.one_server(false)trueWhether one process of the deployment runs it per minute, or every process does.

An entry with a bad expression or timezone, without .run or .job, or with a name already taken is refused when the application boots.

Configure the ticker

# config/default.toml
[schedule]
mode = "ticker"           # ticker | external | off
KeyDescription
schedule.modeticker evaluates the entries in the application process; external leaves it to schedule run; off evaluates nothing.

Run the ticker apart

lat schedule run                     # cargo run -- schedule run
lat schedule run --once              # this minute's entries, then exit
acme schedule run                    # the built binary
* * * * * cd /srv/acme && ./acme schedule run --once

Bootstrap::run reads the process’s arguments: serve (the default), queue work or schedule run.

Read the last runs

lat schedule list
for entry in ctx.schedule().list().await? {
    println!("{} next {:?} last {:?}", entry.name, entry.next_run_at, entry.last_status);
}
ctx.schedule().run_now("acme.blog::digest").await?;
FieldHolds
name, expression, timezone, descriptionThe entry as declared.
next_run_atThe next due minute, UTC.
last_started_at, last_finished_atThe last run’s bounds, UTC.
last_statusnever, running, ok, failed or skipped.
last_errorThe last run’s error, when it failed.

run_now(name) runs an entry outside its expression, under the same locks; false when it was skipped.

Grant the Scheduled tasks screen

# a role's permissions
- backend.manage_schedule
PermissionGrants
backend.manage_scheduleSettings → System → Scheduled Tasks: every entry with its expression, timezone, next and last run, status and error, and Run now.

Entries the framework registers

EntryExpressionDoes
laterite.auth::purge0 * * * *Removes expired sessions and stay-signed-in credentials.

Mail

A message names a template and its variables, or carries its own subject and body; send queues it and a worker delivers it through the configured driver.

use laterite_core::mail::Message;

ctx.mail()
    .send(
        Message::template("acme.blog::welcome", serde_json::json!({ "name": "Ada", "link": url }))
            .to("Ada <ada@acme.example>"),
    )
    .await?;
MethodDoes
Message::template(code, vars)A message rendered from the template code.
Message::raw(subject, text, html)A message with its own body; html optional.
.to(addr), .cc(addr), .bcc(addr), .reply_to(addr), .from(addr)Addresses, as Name <address> or bare.
.attach(filename, content_type, bytes)A file.
mail.send(message)Queues it; Pushed::Ran in inline mode.
mail.send_now(message)Renders and delivers here, returning the driver’s error.
mail.envelope(message)What the driver would deliver, rendered and addressed; nothing is sent.
mail.send_test(addr)The built-in test template, delivered here.

Register a template

use laterite_core::mail::MailRegistry;

fn register(&self, registry: &mut Registry) {
    registry.add_mail_template("acme.blog::welcome", include_str!("../mail/welcome.htm"));
    registry.add_mail_layout("acme", include_str!("../mail/layouts/acme.htm"));
    registry.add_mail_partial("signature", include_str!("../mail/partials/signature.htm"));
}
---
subject: Welcome, {{ name }}
layout: default
description: Sent when an account is made.
---
# Hello {{ name }}

Your account on **{{ app_name }}** is ready.

{% set body %}Sign in{% endset %}
{{ partial("button", url=link, body=body) }}
PartHolds
Front mattersubject, layout (default unless set), description; a layout or partial has name.
BodyA template’s body, written as Markdown; a layout’s or partial’s, as HTML.

The plain-text part is made from the body, with each partial’s text form. A message that needs its own text part registers a .txt beside the .htm:

registry.add_mail_template_with_text(
    "acme.blog::welcome",
    include_str!("../mail/welcome.htm"),
    include_str!("../mail/welcome.txt"),
);
Welcome {{ name }}.

{{ partial("button", url=link, body="Sign in") }}

A layout’s text wrapper and a partial’s text form register the same way (add_mail_layout_with_text, add_mail_partial_with_text). A layout’s CSS goes in a <style> element in its HTML, reading the brand as {{ brand.button_bg }}.

The older form, a key = "value" header and sections split by a line of == (text, HTML, CSS), still reads and is logged as deprecated.

A layout receives content, subject, app_name, css and brand_css. An undefined variable renders empty. A template edited in the admin keeps its edit until it is reset to the file.

TemplateSent by
laterite::testThe Mail settings’ Send test and lat mail test.
laterite.auth::inviteCreating an operator; name, username, link, expires.
laterite.auth::resetThe Forgot your password page; name, username, link, expires.
PartialArguments
buttonurl, body
panel, table, subcopybody, Markdown
header, footerbody, url (header only)

Configure the transport

# config/default.toml
[mail]
driver = "smtp"            # smtp | log | stub | a registered driver
from = "Acme <no-reply@acme.example>"
# to = "dev@acme.example"  # every message goes here while set

[mail.smtp]
host = "smtp.acme.example"
port = 587
encryption = "starttls"    # starttls | tls | none
username = "apikey"
password = ""              # or LAT__MAIL__SMTP__PASSWORD
timeout_seconds = 30
KeyDescription
mail.driversmtp (the smtp feature of laterite-core, on in lateritecmf), log (kept in the mail log, nothing leaves), stub (kept in memory) or a driver a module registered. Default log.
mail.fromThe sender. Default Laterite <no-reply@localhost>.
mail.toA development override: every message goes to this address instead of its recipients.
mail.smtp.*The server, port, encryption, credentials and timeout.

The Mail settings under Settings → System → Mail lay over these: a blank field keeps the configured value, the password is sealed under the application key, and a save switches the transport at once. Gated by backend.manage_mail.

lat mail test ada@acme.example

Send a test message to me on the settings screen mails the signed-in operator the built-in laterite::test template and shows the driver’s error when it fails.

Edit templates in the admin

# a role's permissions
- backend.manage_mail_templates
- backend.manage_mail
PermissionGrants
backend.manage_mail_templatesSettings → System → Mail Templates: the templates, layouts and partials with a preview, a test send to the signed-in operator, Reset to the file, Delete for one no file registers, and New; Mail Branding: the colours every layout reads, with a preview on the test template.
backend.manage_mailMail (the sender and transport, Send a test message) and Mail Log: the messages the log driver kept, each as text and as HTML, with Clear.
Brand colourLayout property
Page background, content background, panel backgroundbrand.body_bg, brand.content_bg, brand.panel_bg
Header text, headings, text, muted text, footer textbrand.header_color, brand.heading_color, brand.text_color, brand.muted_color, brand.footer_color
Links, button, button text, bordersbrand.link_color, brand.button_bg, brand.button_text_color, brand.border_color

Register a driver

use laterite_core::mail::{MailDriverReg, MailRegistry, Mailer};

fn register(&self, registry: &mut Registry) {
    registry.add_mail_driver(MailDriverReg::new("acme-http", |config, _db| {
        Ok(Arc::new(AcmeHttp::new(&config.smtp.username)))
    }));
}

A driver implements Mailer: a name() and deliver(&Envelope); mail.driver = "acme-http" or the settings screen selects it.

Media Library

The Media tab holds the files a site and its records use: folders, upload, search, a kind filter and a page per file. Opening it takes media.browse.

PermissionGrants
media.browseThe tab.
media.uploadUpload into it.
media.manageRename, retitle, move and crop, and make or remove folders.
media.deleteDelete a file no record links to.
media.delete_linkedDelete a file records still use; the file page lists them.

Grant them from a role like any other permission.

Upload

# config/default.toml
[backend]
upload_extensions = ["jpg", "jpeg", "png", "webp", "svg", "pdf", "css"]

A file whose extension is not listed is refused; an empty list allows images, documents, audio, video, fonts and archives. An SVG is cleaned on the way in. Library uploads go to the disk named public, else media under backend.storage (see Storage Disks). Ticking Private sends them to the disk named private, else private under backend.storage.

FileServed at
Public/storage/media/<hash>/<name>, cacheable.
Private/admin/media-files/<id>/<name>, signed in, for whoever may browse the library or see a record the file is attached to; see Storage disks. A tile carries a lock.

Find a file

ControlNarrows to
FolderThe files in it.
SearchA name, across every folder.
KindImage, Video, Audio, Document, Font or Other; Font is listed once the library holds a font.
SortNewest, oldest, name or size.

Manage folders and files

ActionWhereNeeds
Make, rename, move or remove a folderThe folder barmedia.manage; an empty folder only.
Retitle, rename or move a fileThe file pagemedia.manage
Crop an imageThe file pagemedia.manage; a new file <stem>-crop.<ext> beside it, or the file replaced.
Make private, make publicThe file pagemedia.manage; the file moves disk and its thumbnails are made again.
Delete a fileThe file pagemedia.delete, or media.delete_linked when records use it.

Work the library from code

use laterite_media::library::{self, Listing, Sort};
use laterite_media::{folder, record, Kind};

let photos = folder::create(&db, None, "Photos").await?;
let year = folder::create(&db, Some(photos.id), "2026").await?;   // path /Photos/2026
folder::rename(&db, year.id, "2027").await?;
folder::move_to(&db, year.id, None).await?;
folder::delete(&db, year.id).await?;                                // empty folders only
let crumbs = folder::ancestors(&db, year.id).await?;

let page = library::list(&db, &Listing {
    folder: Some(photos.id),
    search: None,
    kind: Some(Kind::Image),
    sort: Sort::Newest,
    page: 1,
    per_page: 60,
}).await?;

record::update_details(&db, id, Some("Our cat"), Some("A tabby")).await?;
record::rename(&db, id, "cat.png").await?;
record::move_to_folder(&db, id, Some(photos.id)).await?;
let has_fonts = library::has_kind(&db, Kind::Font).await?;
let unused = record::set_disk(&db, id, "private").await?;           // after copying the blob
record::set_in_library(&db, id, true, None).await?;
CallRefused when
folder::create, folder::renameThe name has a slash or a control character, or a sibling has it.
folder::move_toThe target is the folder or below it.
folder::deleteThe folder still holds a file or a folder.

Listing.search looks across every folder; Kind::of(content_type) gives Image, Video, Audio, Document or Other.

Media Field

A media field holds one file, or a list of files, picked from the library.

fields:
  cover_id: { type: media, label: Cover, mode: image }
  gallery: { type: media, label: Gallery, max: 6 }
  fonts: { type: media, label: Fonts, mode: font, max: 0 }
  logo_id: { type: media, label: Logo, mode: image, public: true }
OptionDefaultMeaning
modefileimage offers images alone and shows thumbnails; font offers font files alone.
max1How many files the field holds: 1 stores one id in a bigint column; any other number stores a JSON list in a text column, 0 meaning no limit.
publicfalseThe file is shown to people who are not signed in: the picker marks a private file and does not take it, a save refuses one, and a file the field holds cannot be made private.

A save links the picked files to the record under the field’s name; a settings screen links them to its code. The file page lists the screens and fields that use a file, and deleting such a file needs media.delete_linked.

EventDetail
lat:media:changed{ids}, after a pick, a removal or a clear.
use laterite_media::{link, Owner};

let owner = Owner { owner_type: "acme_posts", owner_id: "7", field: "gallery" };
link::set(&db, owner, &media_ids).await?;                           // in that order
let held = link::of_owner(&db, owner).await?;
let users = link::users_of(&db, first).await?;
link::clear_owner(&db, "acme_posts", "7").await?;
CallDoes
link::set(db, owner, media_ids)Replaces what the owner’s field holds with media_ids, in that order.
link::of_owner(db, owner)The ids the owner’s field holds.
link::users_of(db, id)Every owner linking the file.
link::clear_owner(db, owner_type, owner_id)Drops every link a record holds.

Direct Uploads

A direct upload sends the bytes from the browser straight to a disk that presigns, and the application records the file once it has landed.

POST /admin/media/direct            name=clip.mp4&content_type=video/mp4&size=52428800
→ {"direct": true, "url": "<presigned PUT>", "path": "quarantine/<id>/clip.mp4", "headers": {"Content-Type": "video/mp4"}}
PUT <presigned PUT>                 the bytes, from the browser
POST /admin/media/direct/complete   path=quarantine/<id>/clip.mp4&name=clip.mp4&folder=3
→ {"stored": [{"id": 7, "name": "clip.mp4", "href": "/admin/media/7", "url": "..."}], "refused": []}
StepOn a disk that presignsOn any other disk
directA PUT URL under quarantine/<32 hex>/<name>, good for an hour.{"direct": false}: the uploader posts the file instead.
completeThe object is checked, recorded and removed from quarantine/.The same, for an object already under quarantine/.

Turn it on

The upload zone does this on its own when it carries upload_direct, the URL of the direct route (see Receive an upload). The library’s own upload carries it. A path outside quarantine/, or an object larger than the upload limit, is refused.

Abandoned quarantine objects are the bucket’s to expire: set a lifecycle rule of one day on the quarantine/ prefix.

Presign from a driver

MethodDefaultOn S3Disk
StorageDriver::presigned_put(path, content_type, expires_in)NoneA presigned PUT.
StorageDriver::copy(from, to)get then putA server-side copy.

A driver returning None from presigned_put answers {"direct": false}.

Image Variants

A preset names a size and format an image serves at; the variant renders on its first request.

use laterite_media::{Format, Preset};

registry.add(Preset::new("card").width(600).height(400).crop());
registry.add(Preset::new("hero").width(1600).format(Format::WebP).quality(85));
<img src="/storage/media/{{ hash }}/card/{{ name }}" width="600" height="400">
BuilderDefaultMeaning
Preset::new(name)The name in the URL.
.width(px), .height(px)unboundedThe box.
.fit()yesInside the box, keeping the aspect ratio; a smaller source stays its size.
.crop()Filling the box, cropped from the centre.
.exact()The box, stretched.
`.format(Format::AutoJpegPng
.quality(1..=100)82JPEG quality.

Override a built-in preset

Built inBoxUsed by
thumb320 × 320, fitThe library grid.
preview1200 × 1200, fitThe file page.

A registered preset with a built-in name replaces it. An undeclared name is a 404. A file that is not an image serves as it is under any preset.

Keep within the limits

LimitValue
Side12 000 pixels.
Pixels50 million.

An image past either limit serves as it is. A variant renders upright, whatever orientation the camera recorded; width and height are recorded on upload.

Render from code

let prepared = laterite_media::image::prepare(bytes);
let rendered = laterite_media::image::render(&bytes, &preset, prepared.orientation)?;
let made = variants.ensure(&db, disk.as_ref(), &record, &preset).await?;

Crop an image

POST /admin/media/<id>/crop   x=100&y=50&w=200&h=100&mode=new
FieldMeaning
x, y, w, hThe area kept, in the image’s own pixels, clamped to it.
modenew (the default): a file named <stem>-crop.<ext> in the same folder. replace: this file changes in place and its variants are dropped.

The format is kept (PNG, JPEG, WebP; anything else becomes PNG). The file page offers the dialog on an image to a user with media.manage.

let out = laterite_media::image::crop(&bytes, Rect { x, y, width, height }, orientation)?;
laterite_media::record::replace_blob(&db, id, &hash, size, &content_type, width, height).await?;

Maintenance

lat media removes files nothing links to and checks every stored file against its record.

lat media gc                 # files outside the library that nothing links to
lat media gc --grace 1       # younger than one hour is left alone (default 24)
lat media gc --dry-run       # list, remove nothing
lat media verify             # check every stored file against its record
FlagDefaultMeaning
--grace <hours>24A record younger than this is never garbage.
--dry-runoffPrints id, disk, hash and name; removes nothing.
--storage <dir>backend.storageWhere the media and private disks live.

Collect garbage

A file is removed with the last record naming it. A record on a disk the command cannot reach (one the application registered itself) is skipped and counted. From code:

let report = laterite_media::gc::collect(&db, &disks, chrono::Duration::hours(24)).await?;

Verify stored files

verify exits non-zero on a fault and prints one line per faulty record: missing, content mismatch, or a size the record disagrees with. From code:

let report = laterite_media::verify::run(&db, &disks).await?;

Delete a record

if laterite_media::record::delete(&db, id).await? {
    disk.delete(&blob_path(&hash)).await?;
}

delete returns whether the file is now unreferenced. Deleting a file already gone succeeds.

Themes

A theme is a set of templates edited from the admin and served as the site; this page covers the module, the Themes screen, a theme’s config and preview image, its templates and revisions, and the active and edit theme. Register the module and its tables migrate with the application’s:

use lateritecmf::prelude::*;
use lateritecmf::web::theme::ThemeModule;

Bootstrap::new("config")
    .module(ThemeModule)
    .module(migrations::AppModule)
    .run()
    .await

Create a theme from its YAML config, add templates, and make it the site’s theme:

use lateritecmf::web::theme::{self, store, Kind};

let site = store::create_theme(&db, "acme", "name: Acme\nauthor: Acme\n").await?;
store::save_template(&db, site.id, Kind::Layout, "default.htm", None, LAYOUT, None).await?;
store::save_template(
    &db,
    site.id,
    Kind::Page,
    "home.htm",
    Some(serde_json::json!({ "url": "/", "layout": "default" })),
    HOME,
    Some(operator_id),
)
.await?;
theme::set_active_theme(&db, "acme").await?;

Mount the screen

ThemeModule registers the Themes tab at /admin/themes under the permission web.manage_themes, granted to the Administrator role.

SettingDefaultMeaning
backend.paths."laterite.theme/themes"/themesWhere the tab mounts under the admin, as a deployment override.

A module’s own screen audits through the route context:

ctx.audit(&user, "acme.thing.save", Some("thing"), Some(&id), Some(&label), None).await;

Write the config

name: Acme
author: Acme
homepage: https://acme.example
description: The Acme site.
parent: base
require:
  - acme.blog
form:
  fields:
    site_name:
      label: Site name
      default: Acme
KeyTypeDefaultMeaning
namestring""The theme’s display name.
authorstring""Who made it.
homepagestring""The author’s site.
descriptionstring""One line about the theme.
previewstringnoneA URL for the image on the theme list; the initials stand in without one.
parentstringnoneThe theme whose templates fill in for the ones this theme lacks (see Child Themes).
requirelist of module ids[]The modules the theme’s templates need.
formform descriptornoneThe theme’s own settings fields (see Theme Settings and Form Descriptor).

A key outside this table is refused. ThemeConfig::parse reads the YAML and ThemeConfig::to_yaml writes it.

Add a preview image

name: Acme
preview: https://acme.test/themes/acme/preview.png
PropertyStandard
Size1200 × 800 pixels. Minimum 600 × 400.
Aspect3:2, exactly.
FormatPNG or JPEG. WebP is accepted.
WeightUnder 300 KB.
SubjectThe home page as the theme renders it, cropped from the top of the viewport at 1200 pixels wide.
FramingNo browser chrome, device frame, drop shadow, border or rounded corners: the image edges are the page edges.
OverlaysNo added text, badges, logos or colour swatches.
ContentRepresentative content and real images; no placeholder blocks.
Colour schemeLight, unless the theme is dark only.
TransparencyNone: an opaque image.
Shown at184 pixels wide on the theme list, so headings and large shapes must still read at that size.

A theme without preview shows its initials on the theme list.

Save a template

KindPathHolds
Kind::LayoutlayoutThe frame a page renders inside (see Layouts and Partials).
Kind::PagepageA page served at its URL (see Pages).
Kind::PartialpartialA fragment a layout or page includes.
Kind::ContentcontentA block of HTML, Markdown or text (see Content).
Kind::AssetassetA text file the site serves (a stylesheet, a script).

A path is /-separated segments of lowercase letters, digits, dots, hyphens and underscores, at most 255 characters. settings is a JSON object; None keeps the current one.

// A theme's own templates, or those of one kind.
let all = store::list_templates(&db, site.id, None).await?;
let pages = store::list_templates(&db, site.id, Some(Kind::Page)).await?;

store::delete_template(&db, template.id).await?;
URLServes
/themes/<code>/assets/<path>The theme’s text asset, rendered, with an ETag and public, no-cache.

Restore a revision

Every save keeps what it replaced:

let revisions = store::revisions(&db, template.id).await?; // newest first
let restored = store::restore_revision(&db, revisions[0].id, Some(operator_id)).await?;

Manage themes

let all = store::list_themes(&db).await?;
let one = store::find_theme(&db, "acme").await?;
store::update_theme_config(&db, "acme", "name: Acme\nparent: base\n").await?;
store::set_locked(&db, "acme", true).await?;
let copy = store::duplicate_theme(&db, "acme", "acme-copy").await?;
let child = store::create_child_theme(&db, "acme", "acme-child", "Acme child").await?;
store::delete_theme(&db, "acme-copy").await?;
CallRefused when
create_themeThe code is taken, is not lowercase letters, digits and hyphens, or the parent is missing or leads back to the theme.
update_theme_configThe theme is locked, or the parent is missing or leads back.
save_template, delete_templateThe theme is locked, or the path is not a template path.
delete_themeThe theme is active, locked, or another theme’s parent.

Set the active and edit theme

theme::set_active_theme(&db, "acme").await?;
let live = theme::active_theme(&db).await?;

theme::set_edit_theme(&db, operator_id, Some("acme-next")).await?;
let editing = theme::edit_theme(&db, operator_id).await?; // the operator's choice, else the active theme
theme::set_edit_theme(&db, operator_id, None).await?;

A visitor sees the active theme. A user signed in to the admin with web.manage_themes sees their edit theme and its hidden pages, and reads this.preview as true (see Properties).

Replace the site

ThemeModule serves the active theme’s pages at every URL the admin and the other public routes leave. A module of your own takes the site’s place through PublicRouteReg::site:

registry.add_public_route(PublicRouteReg::site(Arc::new(MySite)));
let operator = ctx.operator(&headers).await;     // the session cookie's operator, if any
let person = ctx.identity(user_id).await;        // an active operator by id, for a token the route issued
ctx.record_unserved("GET", "/missing", 404).await; // into the request log

Pages

A page is a template served at its URL; its settings name the URL pattern, the layout, the head’s meta fields and whether it is hidden.

{
  "url": "/blog/:slug",
  "layout": "default",
  "title": "A post",
  "description": "",
  "meta_title": "",
  "meta_description": "",
  "meta_image": "",
  "meta_type": "",
  "meta_robots": "",
  "hidden": false
}
KeyDefaultMeaning
urlrequiredThe URL pattern.
layoutnoneThe layout by name (default for layouts/default.htm); the page then fills its page block, and a block the page defines at its top level fills the layout’s block of that name without rendering in place. A page that writes {% extends %} itself is left as written.
title, description""The page’s own words, read as this.page.title.
meta_title, meta_description, meta_image, meta_type, meta_robots""The head’s meta fields.
hiddenfalseServed only to an operator previewing the theme.
componentsnoneThe components attached to the page, by alias (see Components).

The save refuses a pattern that does not parse or a layout the theme and its ancestors lack.

Write a URL pattern

PatternMatches
/blog/blog, in any case
/blog/:slugone segment, bound to slug
/blog/:slug?the segment or nothing
/blog/:page?1the segment, or 1 when left out
`/blog/:id^[0-9]+$`
/docs/:path*one or more segments, joined with /
/docs/:path?*none or more segments

An optional parameter before a required one is required. One wildcard at most, with no expression and nothing optional after it. The most specific page wins: more static segments, then fewer wildcards, then fewer parameters. The parameters are read as this.params (see Properties).

{% block title %}{{ this.page.title }}{% endblock %}
<a href="{{ page('blog/post', slug=post.slug) }}">{{ post.title }}</a>
NameGives
page(<name>, param=value, ...)The URL of the page named by its path without the extension; a parameter left out takes its default.
{% block page %} in a layoutWhere the page renders (see Layouts and Partials).

The other functions are listed under Functions.

Resolve a URL from Rust

let engine = Engine::build(&db, "acme").await?;
if let Some((name, params)) = engine.resolve("/blog/hello") {
    let settings = engine.page(name);
    let url = engine.url_for(name, &params);
}
for (name, url) in engine.routes().fixed() {
    println!("{name} at {url}");
}

router::Pattern::parse, Pattern::matches, Pattern::url and router::RouteTable are the engine beneath, usable on their own.

Serve the error pages

Page atServes
/404An unmatched URL, with status 404.
/errorA page that failed to render, with status 500.

Hide a page

{ "url": "/drafts", "layout": "default", "hidden": true }

A hidden page is served only to a user previewing their edit theme, and the static build skips it.

Layouts and Partials

A layout is the frame a page renders inside; a partial is a fragment a layout or page includes.

{# layouts/default.htm #}
<!doctype html>
<html>
<head>{{ head }}</head>
<body>
  {% include "partials/nav.htm" %}
  <main>{% block page %}{% endblock %}</main>
</body>
</html>
{# pages/home.htm, with the settings {"url": "/", "layout": "default"} #}
{% block title %}{{ this.page.title }}{% endblock %}
<h1>{{ this.page.title }}</h1>
{{ partial("card.htm", title="Acme", body=page.body) }}
NameGives
layout in a page’s settingsThe layout by name (default for layouts/default.htm); the page then fills its page block, and a block the page defines at its top level fills the layout’s block of that name without rendering in place. A page that writes {% extends %} itself is left as written.
{% block page %} in a layoutWhere the page renders.
{% extends "layouts/<path>" %}, {% block %}A page inside a layout.
{% include "partials/<path>" %}A partial with the current variables.
partial(<path>, name=value, ...)A partial with the named variables, the request’s this and head, and the globals.

Name a template

KindName
Kind::Layoutlayouts/default.htm
Kind::Pagepages/home.htm
Kind::Partialpartials/nav.htm
Kind::Assetassets/css/site.css

A theme’s own template is used, else the nearest ancestor’s (see Child Themes).

Save a layout or partial from Rust

store::save_template(&db, site.id, Kind::Layout, "default.htm", None, LAYOUT, None).await?;
store::save_template(&db, site.id, Kind::Partial, "nav.htm", None, NAV, None).await?;

The path rules and the other calls are under Themes.

Give a partial a role

Partial atRole
partials/<alias>/default.htmThe markup of the component attached under <alias> (see Components).
partials/<code>/default.htmThe markup of the component offered as the snippet <code> (see Snippets).
A partial with snippet in its settingsAn insertable block in the rich and markdown editors (see Snippets).

Content

A content block is a file of HTML, Markdown or text a template inserts with content(); the content filter expands snippets in stored HTML.

{{ content("intro.md") }}
{{ content("welcome.htm", name=this.params.name) }}
{{ post.body|content }}
{# content/welcome.htm #}
<p>Welcome, {name}.</p>
NameGives
content(<path>, name=value, ...)A content block: .md rendered to HTML, .htm and .html as they are, anything else escaped as text; {name} in the block is the named variable, escaped.
<html>|contentSnippets in stored HTML expanded (see Snippets); content(<path>) does the same for a block.
ExtensionRendered as
.mdHTML, as the markdown filter renders it.
.htm, .htmlAs written.
Any otherText, escaped.

Save a content block from Rust

store::save_template(&db, site.id, Kind::Content, "intro.md", None, "# Welcome\n", None).await?;

The path rules and the other calls are under Themes.

Components

A module ships a component; a page or layout attaches it in its settings under components, keyed by the alias the template reads it as.

use lateritecmf::web::theme::component::{
    Component, ComponentContext, ComponentOutput, ComponentReg, PropertyDef, PropertyKind,
};
use lateritecmf::web::theme::ThemeError;
use std::sync::Arc;

struct Posts;

#[lateritecmf::core::strata::async_trait]
impl Component for Posts {
    fn properties(&self) -> Vec<PropertyDef> {
        vec![
            PropertyDef::new("limit", "How many", PropertyKind::Number).default(5),
            PropertyDef::new("slug", "Slug", PropertyKind::Text),
        ]
    }
    async fn run(&self, cx: &ComponentContext<'_>) -> Result<ComponentOutput, ThemeError> {
        let limit = cx.properties["limit"].as_u64().unwrap_or(5);
        let items = load_posts(cx.db, limit).await?;
        Ok(ComponentOutput::data(serde_json::json!({ "items": items }))
            .inject("site_name", "Acme"))
    }
}

fn register(&self, registry: &mut Registry) {
    registry.add(ComponentReg::new("acme.posts", "Posts", Arc::new(Posts)));
}
{
  "url": "/blog/:slug",
  "layout": "default",
  "components": {
    "post": { "component": "acme.posts", "limit": 1, "slug": "{{ :slug }}" },
    "latest": { "component": "acme.posts" }
  }
}
<h1>{{ post.items[0].title }}</h1>
{% for item in latest.items %}<li>{{ item.title }}</li>{% endfor %}
<footer>{{ site_name }}</footer>
NameGives
properties()The properties an attachment may set, with kind, required and default; the save refuses an unknown component, an undeclared property, a wrong kind or a missing required one.
run()ComponentOutput::data, read under the alias, and .inject(name, value) for the page scope.
cx.propertiesThe attached values, {{ :name }} resolved from the URL and defaults filled.
cx.db, cx.params, cx.path, cx.theme, cx.previewThe request.

A layout’s components run first, then the page’s; a page alias replaces a layout’s.

Ship markup with a component

A component may ship markup; a theme overrides it per alias:

fn markup(&self) -> Option<&'static str> {
    Some("<ul>{% for item in component.items %}<li>{{ item.title }}</li>{% endfor %}</ul>")
}
{{ component('latest') }}
NameGives
component(<alias>)The theme’s partials/<alias>/default.htm, else the component’s own markup, with the data as component and under the alias, beside this and head.

Offer a component as a snippet

ComponentReg::snippet lists the component in the editors’ Insert menu; see Snippets.

Build a static site with components

build::build_with takes the registered components for a static build; see Static Build.

Snippets

A snippet is an insertable block in the rich and markdown editors, backed by a partial or by a component.

{
  "snippet": {
    "code": "youtube",
    "name": "YouTube video",
    "description": "Embeds a video by its URL",
    "properties": [
      { "code": "url", "title": "Video URL", "type": "string" },
      { "code": "size", "title": "Size", "type": "dropdown", "options": "sm:Small | lg:Large", "default": "sm" },
      { "code": "autoplay", "title": "Autoplay", "type": "checkbox", "default": false }
    ]
  }
}
{# partials/snippets/youtube.htm #}
<iframe src="https://www.youtube.com/embed/{{ url|replace("https://www.youtube.com/watch?v=", "") }}{% if autoplay %}?autoplay=1{% endif %}" class="video video--{{ size }}"></iframe>
{{ post.body|content }}
KeyValuesDefault
codeletters, digits, ., -, _required
name, descriptionshown in the Insert menudescription optional
properties[].codethe variable name in the partialrequired
properties[].titlethe dialog’s labelrequired
properties[].typestring, dropdown, checkboxstring
properties[].defaultthe value when unsetnone
properties[].optionsvalue:Label | value2:Label2 for a dropdownnone

Declare a snippet on a partial

A partial becomes a snippet through the snippet key of its settings, as above. In the HTML an editor saves, an inserted snippet is <figure data-snippet="youtube" data-properties="{...}"></figure>; \|content renders the partial with each property as a variable beside this and head. A snippet no partial declares renders as an HTML comment naming it.

Declare it from the partial page

The partial’s page carries the declaration as fields under Snippet.

FieldWrites
Codesnippet.code; blank withdraws the snippet.
Name, Descriptionsnippet.name, snippet.description
PropertiesOne row per property: Code, Title, Type, Default, Options. A checkbox default of true, 1, on or yes is stored as true.

Back a snippet with a component

registry.add(
    ComponentReg::new("acme.map", "Map", Arc::new(Map))
        .snippet("Map", Some("A map centred on an address")),
);
{# partials/acme.map/default.htm, else the component's own markup #}
<div class="map" data-lat="{{ component.lat }}" data-lng="{{ component.lng }}"></div>
StepDoes
.snippet(name, description)Lists the component in the Insert menu; its properties are the dialog’s fields (Bool a checkbox, the rest text).
|contentLeaves the figure in place.
After the page rendersEach distinct figure runs the component with its properties (text read to the declared kinds) and renders partials/<code>/default.htm, else the component’s markup, with component, the code, this and head.
A failureAn HTML comment naming the snippet.

The component’s properties and markup are described under Components.

Theme Settings

A theme declares its own settings under form in the config; the theme page shows them as a form, and templates read the values beside the theme’s keys.

name: Acme
form:
  fields:
    site_name:
      label: Site name
      type: text
    tagline:
      label: Tagline
      type: textarea
<h1>{{ theme.site_name }}</h1>
<p>{{ theme.tagline }}</p>
KeyMeaning
formA form descriptor (see Form Descriptor); the fields are listed under Form Fields.
theme.<field>The saved value, read in any template beside theme.code, theme.name, theme.author, theme.homepage and theme.description (see Properties).

A child theme without a form uses its parent’s; the values are each theme’s own. A field named code, name, author, homepage or description is refused.

Read and save the values from Rust

let chain = store::chain(&db, "acme").await?;
let fields = store::form_fields(&chain);
store::save_settings(&db, "acme", &serde_json::json!({ "site_name": "Acme" })).await?;
let values = store::find_theme(&db, "acme").await?.unwrap().settings;

Render the form on a module screen

A module’s own screen renders and collects such a form through the route context:

let form = ctx.value_form(&fields, "acme")?;
let markup = form.render(&values, &shell);
let saved = form.collect(&data)?;
let page = shell.page_with(PageHead::new(title).assets(&form.assets()), markup);

form.assets() lists the scripts and styles the fields’ types declare; pass them to the page head.

Child Themes

A child theme names a parent in its config and uses the parent’s templates for the ones it lacks.

name: Acme child
parent: acme
let child = store::create_child_theme(&db, "acme", "acme-child", "Acme child").await?;
KeyTypeDefaultMeaning
parentstringnoneThe theme whose templates fill in for the ones this theme lacks.
LookupResult
A template by kind and pathThe theme’s own, else the nearest ancestor’s.
A page’s layoutAny layout of the theme or its ancestors.
The settings formThe theme’s own, else its parent’s; the values are each theme’s own (see Theme Settings).

Resolve a template through the chain

// Through the parent chain: the theme's own row, else the nearest ancestor's.
if let Some((from, template)) = store::resolve_template(&db, "child", Kind::Layout, "default.htm").await? {
    println!("{} from {}", template.path, from.code);
}

let chain = store::chain(&db, "child").await?;

Change or remove a parent

store::update_theme_config(&db, "acme-child", "name: Acme child\nparent: base\n").await?;
CallRefused when
create_themeThe parent is missing or leads back to the theme.
update_theme_configThe theme is locked, or the parent is missing or leads back.
delete_themeThe theme is another theme’s parent.

The other calls are under Themes.

Export and Import

A theme travels as a zip of its config, settings values and templates, written by lat theme export and read by lat theme import.

lat theme list
lat theme export acme
lat theme export acme --out themes/acme.zip
lat theme import acme themes/acme.zip
lat theme import acme themes/acme.zip --replace
acme.zip
├── theme.yaml
├── settings.json         # the theme's settings values, when it has any
├── layouts/default.htm
├── pages/home.htm
├── partials/nav.htm
├── content/intro.md
└── assets/css/site.css

A template with settings carries them as YAML front matter between --- lines:

---
url: /
layout: default
---
{% extends "layouts/default.htm" %}
Flag or fieldMeaning
--replace, Replace templatesReplace the templates and the config the theme already has; each replaced template keeps a revision. Without it, an existing template is skipped.
codeThe theme to import into; created from theme.yaml when it does not exist.

Export and import from Rust

use lateritecmf::web::theme::archive;

let bytes = archive::export(&db, "acme").await?;
let report = archive::import(&db, "acme-copy", &bytes, false, Some(operator_id)).await?;
println!("{} written, {} skipped", report.imported, report.skipped);

ImportReport carries created, imported, skipped and ignored (files that are not templates).

Static Build

lat theme build writes a theme’s pages and text assets to a directory any static host serves.

lat theme build acme
lat theme build acme --out public --base-url https://acme.example

Every page whose URL has no parameter is written at its URL (/about to about/index.html), the /404 page also as 404.html, a page whose URL names a file (/robots.txt, /sitemap.xml) as that file, and the text assets under themes/<code>/assets/. A clean URL’s canonical link and this.url carry the trailing slash a static host serves it with (/about/). A page with parameters or a hidden page is skipped and named.

FlagDefaultMeaning
--outdistThe output directory.
--base-urlthe application’s app.url, else one derived from server.listenThe origin url() and the canonical link use.
--from <DIR>the project’s theme.folderBuild a theme folder with no application; the folder’s name is the code. See Static Website.
--copy <SRC>:<DEST>the project’s theme.copyA directory copied into the output at <DEST>. Repeatable.

Preview a theme folder

lat theme serve
lat theme serve --from themes/acme --listen 127.0.0.1:3000 --copy docs/book:docs
FlagDefaultMeaning
--from <DIR>the project’s theme.folderThe theme folder.
--listenthe project’s server.listen, else 127.0.0.1:8080The address.
--copy <SRC>:<DEST>the project’s theme.copyAs build --copy.

lat serve in a project with theme.folder is this preview.

Load a theme folder from Rust

use lateritecmf::web::theme::{build, folder};

let loaded = folder::load(Path::new("themes/acme")).await?;
let report = build::build(&loaded.db, &loaded.code, Path::new("dist"), "https://acme.example").await?;
FieldHolds
dbA private in-memory database holding the theme.
codeThe folder’s name.
reportThe ImportReport of the load.

Build from Rust

use lateritecmf::web::theme::build;

let report = build::build(&db, "acme", Path::new("dist"), "https://acme.example").await?;
println!("{} pages, {} assets, {} skipped", report.pages.len(), report.assets.len(), report.skipped.len());

Build from the application

lat theme build renders without an application’s modules; a template that needs their markup or components is built from the application with build::build_with:

let report = build::build_with(
    &db,
    "acme",
    Path::new("dist"),
    "https://acme.example",
    &[Arc::new(Money)],
    &[&ComponentReg::new("acme.posts", "Posts", Arc::new(Posts))],
)
.await?;
ArgumentMeaning
markupThe Markup registrations to install, in order.
componentsThe ComponentReg registrations the pages attach.

A site rendered by your own templating, with no theme, is covered under Static Site Generation.

Maintenance Mode

Maintenance mode answers every visitor with the theme’s /maintenance page, or a plain notice, until it is switched off.

use lateritecmf::web::theme::maintenance::MaintenanceSettings;

let settings: MaintenanceSettings = lateritecmf::admin::settings::load(&db).await?;

Settings › Website › Maintenance Mode, under web.manage_site:

FieldMeaning
Show visitors the maintenance pageOn, a visitor gets status 503 with Retry-After: 600.
MessageThe plain notice’s text, when the theme has no page at /maintenance.
Page atServes
/maintenanceEvery visitor’s request while the mode is on.

Keep working while it is on

A user with web.manage_themes sees the site as usual, with a bar at the foot of every page.

Link on the barOpens
View as a visitorThe same path with ?maintenance=visitor: the maintenance page, status 503.
Turn it offThe Maintenance Mode settings screen.
Back to the siteThe path without the query, from the visitor’s view.
<div role="status" data-laterite-maintenance>...</div>

The bar sits before </body>, or at the end of a document without one.

Interactive Pages

A page posts to a component’s handler and swaps the answer into place; the component declares its handlers, the template attaches them.

use laterite_web::theme::component::{Component, ComponentContext, ComponentOutput, Handled, HandlerContext};

#[async_trait]
impl Component for Todo {
    async fn run(&self, cx: &ComponentContext<'_>) -> Result<ComponentOutput, ThemeError> {
        Ok(ComponentOutput::data(json!({ "items": load(cx.db).await? })))
    }
    fn handlers(&self) -> &'static [&'static str] {
        &["add"]
    }
    async fn handle(&self, name: &str, cx: &HandlerContext<'_>) -> Result<Handled, ThemeError> {
        let mut items = cx.input.list("items");
        let item = cx.input.text("new_item").to_string();
        if item.is_empty() {
            return Ok(Handled::invalid("new_item", "Say what to add.").with_data(json!({ "items": items })));
        }
        if items.len() as u64 >= cx.property_u64("max", 10) {
            return Ok(Handled::invalid("new_item", "The list is full."));
        }
        items.push(item);
        Ok(Handled::data(json!({ "items": items })).inject("saved", true))
    }
}
{{ framework() }}
<form {{ request('todo::add', target='#todo') }}>
  {{ token('todo::add') }}
  {% for item in todo.items %}<input type="hidden" name="items[]" value="{{ item }}">{% endfor %}
  <input name="new_item">
  <button>Add</button>
</form>
<div id="todo">{{ component('todo') }}</div>
{# partials/todo/default.htm #}
<ul>{% for item in component.items %}<li>{{ item }}</li>{% endfor %}</ul>
{% if errors.new_item %}<p class="error">{{ errors.new_item }}</p>{% endif %}

Declare a handler

MethodGives
handlers()The names a page may post to. A name not listed is a 404.
handle(name, cx)The outcome for one post, after run has produced the component’s data.
cx.input.text(name)The first value under name, trimmed; empty when absent.
cx.input.list(name)Every value under name or name[].
cx.input.has(name)Whether the field was posted.
cx.property_u64(name, default)A number property of the attachment.
cx.properties, cx.params, cx.path, cx.headers, cx.db, cx.previewThe request, as run sees it.

Return an outcome

OutcomeRenders
Handled::data(value)The alias with value as its data; .inject(name, value) adds a page variable.
Handled::invalid(field, message)Status 422 with errors.<field> in scope; .with_data(value) sets the alias’s data.
.flash(level, text) on data or invalidA message for the visitor: flash.level and flash.text in the page scope, and an out-of-band swap into <div id="flash"> for HTMX.
Handled::Redirect(url)HX-Redirect for HTMX, a 303 otherwise.
Handled::Json(value)The value as application/json.
Handled::UnknownA 404.

Attach it in a template

FunctionEmits
framework()The script at /laterite/htmx.js, which also swaps a 422 into place. No inline script, so a script-src 'self' policy runs it.
request(handler, target=, swap=, partial=, confirm=, indicator=)hx-post to the page, hx-headers naming the handler and the partial, hx-vals with the visitor’s token, and the HTMX attributes given.
token(handler)The hidden _token and _handler fields, for a form that posts without a script.
component(alias)The alias’s markup: partials/<alias>/default.htm, else the component’s own.

partial names a theme partial to render in place of the alias’s markup, with the page’s scope. Without HTMX the whole page renders, at 200 or 422, and a redirect is a 303.

Read the scope

NameHolds
errorsThe messages by field of a refused input; an empty map otherwise.
laterite_tokenThe visitor’s token; request() and token() read it.
this.urlThe page’s URL, where the post goes.

A post from another site, or without the visitor’s token, is a 403. The token is a cookie set on the first page and lives a day.

Show a flash

<div id="flash">{% if flash %}<p class="flash flash--{{ flash.level }}">{{ flash.text }}</p>{% endif %}</div>

Build it statically

A static build renders a page that attaches a component with handlers and warns, naming the page: a static host answers no post. Serve the site from the application, or keep such pages off a static host.

Colour Mode

A site offers light, dark, or follow the system, resolved before the first paint and kept in step with the system while the page is open.

<head>
  {{ colour_mode() }}
  <link rel="stylesheet" href="{{ asset('css/site.css') }}">
</head>
html[data-theme="dark"] { color-scheme: dark; background: #111; color: #eee; }
html[data-theme="light"] { color-scheme: light; background: #fff; color: #111; }
<button onclick="latSetMode('dark')">Dark</button>
<button onclick="latSetMode('light')">Light</button>
<button onclick="latSetMode('auto')">System</button>
FunctionEmits
colour_mode()The inline script, to place before any stylesheet.
colour_mode(file=true)A <script src="/laterite/theme-boot.js"> tag, for a Content Security Policy that forbids inline scripts; the site serves the file and a static build writes it.
NameHolds
<html data-theme="light">The resolved mode; write CSS against it.
localStorage["lat-mode"]The reader’s choice: light, dark or auto.
latMode()The current choice.
latSetMode(mode)Persists a choice and applies it.
latApplyMode(mode)Applies a mode without persisting it.

Use it from Rust

use laterite_core::theme;

let head = format!("<head>{}<link rel=\"stylesheet\" href=\"/site.css\"></head>", theme::boot_markup());
NameGives
theme::boot_markup()The inline <script> element.
theme::BOOT_JSThe script alone, to serve as a file or embed with a nonce.
theme::MODE_KEYlat-mode.
theme::MODES["light", "dark", "auto"].

A deferred or external script runs after the first paint, and a dark-mode reader sees the page flash white; the inline form avoids that.

Static Site Generation

laterite-web renders an application’s public pages to HTML at build time, into a directory any static host serves.

[dependencies]
laterite-web = "0.12"
TypeRole
MetaThe shared <head> tags: title, description, canonical URL, Open Graph and Twitter card.
StaticSiteCollects rendered pages, copies assets, and reports what it wrote.

Templating is yours: any renderer that produces an HTML String.

Write a generator

use laterite_web::{Meta, StaticSite};

fn render_home(head: &str) -> String {
    format!("<!doctype html><html><head>{head}</head><body><h1>Acme</h1></body></html>")
}

fn main() -> std::io::Result<()> {
    let base_url = "https://acme.example";

    let meta = Meta::new("Acme", "The Acme website.")
        .canonical(format!("{base_url}/"))
        .image(format!("{base_url}/static/card.png"));
    let home = render_home(&meta.head_tags());

    let mut site = StaticSite::new("dist", base_url)?;
    site.page("/", &home)?;
    site.assets("static", "static")?;
    Ok(())
}

cargo run writes dist/.

Map URLs to files

Path passed to pageFile writtenServed as
/dist/index.html/
/features/dist/features/index.html/features/
/get-starteddist/get-started/index.html/get-started/

Set page metadata

let meta = Meta::new(title, description)
    .canonical(format!("{base_url}{path}"))
    .image(format!("{base_url}/static/img/card.png"));

let head = meta.head_tags();
MethodDescription
new(title, description)Escaped; safe to build from content.
canonical(url)Also the Open Graph URL. Optional.
image(url)The social-share image. Optional.

Publish extra files

let urls: Vec<String> = site
    .paths()
    .iter()
    .map(|path| format!("{}{path}", site.base_url()))
    .collect();

site.file("sitemap.xml", &your_sitemap(&urls))?;
site.file("robots.txt", "User-agent: *\nAllow: /\n")?;
MethodDescription
paths()Every page written, in order.
base_url()The prefix for absolute URLs.
file(path, content)Writes verbatim at the output root. Creates parent directories; refuses a path outside the output.
assets(from, to)Copies a directory recursively.

No robots.txt or sitemap.xml is written for you.

Deploy

dist/ is plain files. On a host that builds from Git: build command cargo run, publish directory dist.

A page whose content depends on the request (a form, a search, per-user content, the admin) stays on the live server. A theme’s pages are built with lat theme build.

Templating

A template extends a layout, fills its blocks, includes partials and content, and reads the theme global.

{% extends "layouts/default.htm" %}
{% block body %}
  {% include "partials/nav.htm" %}
  {{ partial("card.htm", title="Acme", body=page.body) }}
  {{ content("intro.md") }}
  <h1>{{ theme.name }}</h1>
{% endblock %}

Templates are named by the kind’s folder and the path:

KindName
Kind::Layoutlayouts/default.htm
Kind::Pagepages/home.htm
Kind::Partialpartials/nav.htm
Kind::Assetassets/css/site.css

A theme’s own template is used, else the nearest ancestor’s.

NameGives
{% extends "layouts/<path>" %}, {% block %}A page inside a layout (see Tags).
{% include "partials/<path>" %}A partial with the current variables.
partial(<path>, name=value, ...), content(<path>, name=value, ...)A partial or a content block (see Functions).
themecode, name, author, homepage, description of the theme rendered, and its settings (see Properties).

Escape output

HTML is escaped in every template but an asset. A printed undefined value is an error; {% if page.sub %} on an undefined value is not.

Check a template

use lateritecmf::web::theme::{check, RenderError};

match check(source) {
    Ok(()) => {}
    Err(RenderError { line, message, .. }) => println!("line {line:?}: {message}"),
}

RenderError carries template, line, kind and message.

Render from Rust

use lateritecmf::web::theme::{Engine, EngineCache, Kind};

let engine = Engine::build(&db, "acme").await?;
let html = engine.render(Kind::Page, "home.htm", serde_json::json!({ "title": "Home" }))?;
let css = engine.render(Kind::Asset, "css/site.css", ())?;

// One engine per theme, rebuilt when the theme or an ancestor changes.
let cache = EngineCache::new();
let engine = cache.get(&db, "acme").await?;
cache.invalidate("acme");

// The application's own functions, filters and globals.
let engine = Engine::build_with(&db, "acme", |env| {
    env.add_function("year", || 2026);
})
.await?;

Add markup from a module

use lateritecmf::web::theme::markup::{Markup, MarkupReg};
use minijinja::Environment;
use std::sync::Arc;

struct Money;

impl Markup for Money {
    fn install(&self, env: &mut Environment<'static>) {
        env.add_filter("money", |minor: i64| format!("{}.{:02}", minor / 100, minor % 100));
        env.add_function("year", || 2026);
    }
}

fn register(&self, registry: &mut Registry) {
    registry.add(MarkupReg::new("acme.money", Arc::new(Money)));
}
{{ price|money }} in {{ year() }}

Every registration is installed in order. A static build takes the registrations through build::build_with.

Properties

Every page, layout and partial reads the request as this, the page’s head tags as head, and the theme as theme.

<html>
<head>{{ head }}</head>
<body>
  <h1>{{ this.page.title }}</h1>
  <p>{{ this.params.slug }} on {{ this.url }} in {{ this.theme.name }}</p>
  {% if this.preview %}<p>Previewing.</p>{% endif %}
  {% block page %}{% endblock %}
</body>
</html>
NameGives
this.pageThe page’s settings and name (see Pages).
this.paramsThe URL’s parameters.
this.themecode and name.
this.layoutThe layout the page named.
this.urlThe request path.
this.previewWhether an operator is previewing.
headThe title, description, canonical, Open Graph and robots tags from the page’s settings; a setting may carry an expression.
themecode, name, author, homepage, description of the theme rendered.
theme.<field>A value of the theme’s own settings.

Read a component’s data

<h1>{{ post.items[0].title }}</h1>
<footer>{{ site_name }}</footer>
NameGives
<alias>The data a component attached under that alias returned.
<name>A value a component injected into the page scope.
componentInside a component’s markup, its own data.

Tags

A tag is a {% %} statement: a page extends a layout, fills its blocks, includes a partial, loops and branches.

{% extends "layouts/default.htm" %}
{% block page %}
  {% include "partials/nav.htm" %}
  {% for item in latest.items %}<li>{{ item.title }}</li>{% endfor %}
  {% if this.preview %}<p>Previewing.</p>{% endif %}
{% endblock %}
TagGives
{% extends "layouts/<path>" %}A page inside a layout.
{% block <name> %}...{% endblock %}A block the layout defines and the page fills; {% block page %} in a layout is where the page renders.
{% include "partials/<path>" %}A partial with the current variables.
{% for item in items %}...{% endfor %}One pass per item.
{% if value %}...{% endif %}A branch; an undefined value is false.

Fill a layout from a page

{% block title %}{{ this.page.title }}{% endblock %}
<h1>{{ this.page.title }}</h1>

A page whose settings name a layout fills the layout’s page block, and a block the page defines at its top level fills the layout’s block of that name without rendering in place. A page that writes {% extends %} itself is left as written (see Layouts and Partials).

Filters

A filter follows a value after | and transforms it before it prints.

{{ post.body|content }}
{{ post.summary|markdown }}
<img src="{{ post.image|variant('card') }}">
{{ price|money }}
NameGives
<html>|contentSnippets in stored HTML expanded (see Snippets); content(<path>) does the same for a block.
<text>|markdownMarkdown rendered to HTML: CommonMark with tables, strikethrough, footnotes, task lists and {#id} heading attributes; a heading without one gets an id from its text (## Release 0.9 is release-0-9); raw HTML passes through.
<url>|variant("card")A media URL rewritten to the named preset (see Image Variants).

Add a filter from a module

impl Markup for Money {
    fn install(&self, env: &mut Environment<'static>) {
        env.add_filter("money", |minor: i64| format!("{}.{:02}", minor / 100, minor % 100));
    }
}

The registration is described under Templating.

Functions

A function is called in {{ }} and gives a URL, a rendered partial, a content block or a component’s markup.

<a href="{{ page('blog/post', slug=post.slug) }}">{{ post.title }}</a>
{{ partial("card.htm", title="Acme", body=page.body) }}
{{ content("intro.md") }}
<link rel="stylesheet" href="{{ asset('css/site.css') }}">
<link rel="canonical" href="{{ url(this.url) }}">
<img src="{{ media(post.image, preset='card') }}">
{{ component('latest') }}
NameGives
page(<name>, param=value, ...)The URL of the page named by its path without the extension; a parameter left out takes its default (see Pages).
partial(<path>, name=value, ...)A partial with the named variables, the request’s this and head, and the globals.
content(<path>, name=value, ...)A content block: .md rendered to HTML, .htm and .html as they are, anything else escaped as text; {name} in the block is the named variable, escaped (see Content).
asset(<path>)The URL of the theme’s text asset: /themes/<code>/assets/<path>.
url(<path>)The absolute URL of a path on the site, from the deployment’s origin.
media(<file>), media(<file>, preset="card")The URL of a media value (a URL, or an object with url as theme::media_value builds), under a preset when one is named.
component(<alias>)The theme’s partials/<alias>/default.htm, else the component’s own markup, with the data as component and under the alias, beside this and head (see Components).
framework()The request framework’s script and its island (see Interactive Pages).
request(<handler>, target=, swap=, partial=, confirm=, indicator=)The attributes that post a form or element to a component’s handler, with the visitor’s token.
token(<handler>)The hidden fields a form posts to a handler without a script.
colour_mode(), colour_mode(file=true)The colour mode script, inline or as a file (see Colour Mode).

Add a function from a module

impl Markup for Money {
    fn install(&self, env: &mut Environment<'static>) {
        env.add_function("year", || 2026);
    }
}
{{ year() }}

The registration is described under Templating. A static build sets the origin url() uses with --base-url.

Behaviours

What the admin does with no configuration, and the key that changes it.

Forms

WhereDefaultChange it
A single-line fieldEnter submits the form.enter: off on the form; enter: off or enter: next on a field.
A picker or a repeater rowEnter acts inside it.data-lat-enter-scope and data-lat-enter-target on a widget of your own.
A field’s widthThe whole row.span: 1/2, 1/3, 2/3, 1/4, 3/4; break: true.
A repeaterPast 3 fields a row, rows collapse to the line naming them; fewer stay open.display: list or inline.
A repeater rowMoves up and down, copies into a new row beneath it, and is removed.reorder: false, duplicate: false.
A refused saveThe form returns with its errors, values kept (a repeater’s rows and a checklist’s ticks included), and the cursor in the first field it refused.focus: off.
A new recordOpens with the cursor in its first field.focus: off.
Leaving with changes unsavedAsks first, with the cursor on Stay. Typing and undoing it is not a change.confirm_leave: false.
Save and continue editingOffered beside Save on a resource with relations; the save lands on the edit page. A create page names the sections it will have.Declare no relations.
A field with a max_length ruleThe control holds the limit, and a count appears once four fifths of it are used.counter: true or false.
A textareaAs tall as its text, from rows up to most of the window.grow: false.
A password fieldA button shows what was typed. Sending the form hides it again.reveal: false.
A field with presetFollows the named field as it is typed, until edited.Omit the key.
A select past 10 choicesSearched: a box that filters the choices as you type.search: true or false.
A field with triggerShows, hides, enables, disables, empties or fills itself as the watched field changes. A hidden field is left out of the submission.Omit the key.
A checklist past 10 choicesOffers select all and select none.select_all: true or false.
A checklist past 20 choicesOffers a search box.search: true or false.
A checklist past 10 choices, in groupsA group with every box ticked, or none, starts closed. A group partly ticked starts open.expand: all or none.
form:
  enter: off
  confirm_leave: false
  fields:
    sku:   { enter: next, span: 1/3 }
    links: { type: repeater, display: list, fields: { url: { input: url } } }
    tags:  { type: checklist, select_all: false, expand: all, options: [{ value: new }] }

Lists

WhereDefaultChange it
SearchAsks as you type.search: { on_enter: true }; search: { enabled: false }.
Columns and page sizeEach operator’s choice is remembered.per_page sets the size; per_page_options offers a choice of sizes.
A columnSortable, visible, read-only.sortable: false, invisible: true, editable: true.
ExportOff.exportable: true.
Deleting rowsOff.deletable: true; it asks before it deletes.
Rows in an order of their ownOff.reorder: true keeps the order in sort_order; reorder: { column: position } names the column. An integer column, not null, default 0. The list opens in that order with a grip to drag and Move up / Move down on every row; a sorted, searched or filtered view shows neither. A has-many section’s list takes the same key.
Rows as a treeOff.tree: true reads the parent from parent_id; tree: { parent_key: folder_id, source: acme.folders } names the column and a picker source. The list opens on the rows with no parent; a row with children expands in place, or opens them as a page with scripting off. With a source, every row offers “Move to”, which picks the new parent from it or leaves it empty for the top level, and a record never moves under itself. With reorder too, a move stays among one parent’s children.
A rowOpens its record on a click or Enter, when the list has a form. A modified or middle click opens a new tab.row_click: none.
Returning to a listThe sort, search and filters used last come back, for the session. Clearing them forgets them.remember: false.
A stored code in a columnShown as stored.labels: [{ value, label }] shows a label for each value.
list:
  search: { on_enter: true, prompt: Search posts }
  per_page_options: [25, 50, 100]
  exportable: true
  reorder: { column: position }
  tree: { source: acme.pages }
  row_click: none
  remember: false
  columns:
    title: { editable: true }
    status: { labels: [{ value: pub, label: Published }, { value: dr, label: Draft }] }

Messages and dialogs

WhereDefaultChange it
A success or info messageLeaves after five seconds.session.push_flash_sticky(..) keeps it until dismissed.
A control with data-lat-confirmAsks before it acts.Omit the attribute.
A menuCloses on a click outside, a chosen link, or Escape.data-lat-keep-open.

Tooltips

<button type="button" aria-label="Archive"
        data-lat-tooltip="Archive"
        data-lat-tooltip-position="top"
        data-lat-tooltip-hotkey="Ctrl+E, Ctrl+Shift+E">…</button>
AttributeValuesDefault
data-lat-tooltipThe text to show.No tooltip.
data-lat-tooltip-positiontop, bottom, left, rightbottom, or the opposite side when the chosen one has no room.
data-lat-tooltip-hotkeyShortcuts, comma separated, written with Ctrl, Alt, Shift.None. A Mac shows ⌘, ⌥, ⇧.
WhereDefaultChange it
A pointer resting on the elementShows the tooltip after 300 ms.Omit data-lat-tooltip.
Keyboard focusShows the tooltip at once.Omit data-lat-tooltip.
Escape, a click, a scroll, a swapHides the tooltip.None.
TouchNo tooltip; aria-label names an icon-only control.None.
lat.tooltip.show(document.querySelector('#archive'));
lat.tooltip.hide();

Accounts and sessions

WhereDefaultChange it
A new passwordAt least 8 characters.[auth.password_policy] min_length.
A generated passwordTemporary: every screen leads to Preferences until it is replaced.lat admin create without --generate sets a password that is kept.
The top bar’s orderThe registry’s order. An operator drags the tabs into their own, kept with their preferences.“Reset the menu order” on Preferences.
Finding a page or a recordThe search button or Ctrl+K opens the command palette over menu entries, settings and the records of resources with a palette source.palette: <picker source> on a resource adds its records.
Failed sign-ins5 for a username from one address, 20 from one address, in 15 minutes.[auth] max_failures, max_failures_per_address, failure_window_secs.
A sessionEnds after 2 hours idle, or 12 hours.[auth] session_idle_timeout_secs, session_absolute_timeout_secs.
Expired sessionsRemoved hourly.lat admin purge runs it on demand.
[auth]
max_failures = 5
session_idle_timeout_secs = 7200

[auth.password_policy]
min_length = 12

Command Line

lat scaffolds, runs and maintains an application. Every command accepts --database-url <URL>, falling back to DATABASE_URL, then to the configuration of the application found from the current directory upward.

cargo install laterite-cli
lat --help
lat <command> --help

Scaffold

CommandDescriptionOptionsExample
new [NAME]Scaffold and set up a new application, or a static website (interactive).--static: a static website. --content files|folder|git|database: where its content lives, default files. --plugin <SOURCE>: install a plugin, repeatable. --framework-path <PATH>: build against a local framework checkout, also read from LATERITE_FRAMEWORK_PATH. --url, --timezone, --listen, --admin <USERNAME> with --admin-email, --admin-name and the password in LAT_NEW_ADMIN_PASSWORD: answer the prompts up front.lat new "Acme" --static --content git --url https://acme.example --timezone UTC --listen 127.0.0.1:8080 --admin admin --admin-email admin@acme.example --admin-name Ana
make:migration <DESCRIPTION>Scaffold a migration file in this crate’s src/migrations/.--path <PATH>: the crate directory, default ..lat make:migration create_articles
make:plugin <ID>Scaffold a plugin crate; <ID> is vendor.name.--path <PATH>: where to create it, default .. --admin: scaffold the admin half.lat make:plugin acme.blog --admin
make:resource <NAME>Scaffold an entity’s migration, schema, store and admin screen.--path <PATH>: the crate, default .. --field <name:type>: columns beyond id and timestamps; types text, integer, boolean, datetime; repeat or comma-separate. --source <DIR>: keep the records as files in that folder, keyed by a slug column; `–format yamljson
make:model <NAME>Scaffold a typed model struct for a table in src/models/.--path <PATH>: the crate, default .. --field <name:type>: columns beyond id; types text, integer, boolean, datetime. --table <TABLE>: when it is not the plural. See Models.lat make:model article --field title:text,views:integer
seed [MODULE]Run the application’s seeders, or one module’s.--release; -p <PACKAGE>: the binary’s package in a workspace. See Seeding.lat seed acme.blog

Run and check

CommandDescriptionOptionsExample
serveRun this application, or preview a static website’s theme folder, optionally overriding the address.--host <HOST>, --port <PORT>, --listen <HOST:PORT>, --release: build and run optimised.lat serve --port 3000
doctorCheck that this application is set up to run, plugin dependencies included.None.lat doctor
help-appList the application’s commands, its modules’ included.None.lat help-app
any otherRun the application’s command of that name, added by a module (Console Commands).The command’s own.lat pdf check
routesList every URL the application answers: method, path, kind, owner, permission.--path <TEXT>, --method <GET|POST|QUERY>, --kind <resource|screen|settings|public|page|framework>, --owner <MODULE>, --permission <CODE>, --public: keep matching rows, combined. --json: print JSON. --release. -p <PACKAGE>: the binary’s package in a workspace.lat routes --path events --method POST

Local domains

CommandDescriptionOptionsExample
domain setupRoute *.<tld> to 127.0.0.1 via dnsmasq and a macOS resolver entry.--tld <TLD>, default test. --dry-run.lat domain setup --dry-run
domain statusReport the current local-domain DNS state.--tld <TLD>.lat domain status
domain teardownUndo the wildcard DNS configuration.--tld <TLD>. --dry-run.lat domain teardown

Admin users

CommandDescriptionOptionsExample
admin create <USERNAME>Create a superuser.--email <EMAIL> and --first-name <NAME> required; --last-name <NAME>; --password <PASSWORD>, else prompted; --generate: print a strong random password.lat admin create editor --email editor@acme.test --first-name Editor
admin reset-password <USERNAME>Set a new password for a user.--password <PASSWORD>, else prompted; --generate.lat admin reset-password editor --generate
admin listList the admin users.None.lat admin list
admin unlock <USERNAME>Clear a user’s failed-login lockout.None.lat admin unlock editor
admin purgeRemove expired sessions and stay-signed-in credentials.None.lat admin purge

Plugins

CommandDescriptionOptionsExample
plugin add <SOURCE>Add a plugin from a local path or a git URL, and record it.--as <FOLDER>: the folder under plugins/, default the crate’s name. In a static website the first add writes its Cargo project and a plugin needs static = true.lat plugin add ../blog-plugin
plugin remove <NAME>Remove a plugin from the list by crate name or folder.--delete: also delete its folder.lat plugin remove acme-blog --delete
plugin syncRegenerate the plugins-manifest crate from plugins/plugins.toml, then check the plugins’ dependencies.None.lat plugin sync
plugin listList the plugins this application compiles in.None.lat plugin list
plugin checkCheck each installed plugin against the expected layout and its dependencies, listing every crate built twice.None.lat plugin check

Translations

CommandDescriptionOptionsExample
i18n extractRegenerate each crate’s lang/messages.pot from its source strings.None.lat i18n extract
i18n checkFail if any committed messages.pot is out of date.None.lat i18n check
i18n update <LOCALE>Merge each crate’s messages.pot into a locale’s .po, keeping existing translations; creates the .po if absent.None.lat i18n update fr
i18n statusReport translation coverage for each crate’s locale catalogs.None.lat i18n status

Themes

CommandDescriptionOptionsExample
theme export <CODE>Write a theme and its templates to a zip.-o, --out <FILE>, default <code>.zip.lat theme export acme -o acme.zip
theme import <CODE> <FILE>Create or update a theme from a zip.--replace: replace templates and config the theme already has; each replaced template keeps a revision.lat theme import acme acme.zip --replace
theme listList the themes.None.lat theme list
theme build [CODE]Render a theme’s fixed pages and assets to a directory, for a static host.--from <DIR>: a theme folder instead of the database, default theme.folder. -o, --out <DIR>, default dist. --base-url <URL>, default app.url, else one derived from server.listen. --copy <SRC>:<DEST>: a directory copied into the output; repeatable, added to theme.copy.lat theme build --copy docs/book:docs
theme servePreview a theme folder, rebuilt on every change.--from <DIR>, default theme.folder. --listen <HOST:PORT>, default server.listen. --copy <SRC>:<DEST>.lat theme serve
theme publishMake the theme’s saved changes visible to the host: the source’s publish step, then theme.publish.hook.None.lat theme publish

Media

CommandDescriptionOptionsExample
media gcRemove files outside the library that nothing links to, and the blobs no record names any more.--grace <HOURS>: leave younger files alone, default 24. --dry-run. --storage <DIR>, default backend.storage.lat media gc --dry-run
media verifyRe-hash every stored file against its record.--storage <DIR>, default backend.storage.lat media verify

Key

CommandDoes
lat key generateWrites a new application key as app.key in config/local.toml; --rotate keeps the old key under previous_keys, --print prints without writing.
lat key showThe id of the key in use and of the previous keys.
lat crypt rotateRe-seals every sensitive column under the key in use, after lat key generate --rotate.

Cache

CommandDoes
lat cache clearMoves every cache namespace on; every process reads afresh. --namespace records::posts moves one.
lat cache listEvery namespace the deployment knows, with its generation.

Queue

CommandDoes
lat queue workRuns the application’s worker (cargo run -- queue work); --once, --stop-when-empty, --queue high,default, --release.
lat queue listHow many jobs wait and run on each queue.
lat queue failedThe failed list.
lat queue retry <id|all>Puts a failed job back on its queue.
lat queue forget <id|all>Drops a failed job.
lat queue flush [--queue name]Drops every waiting job, or one queue’s.

Schedule

CommandDoes
lat schedule runRuns the application’s ticker (cargo run -- schedule run); --once evaluates this minute and exits.
lat schedule listEvery entry that has run on this deployment, with its last run.

Mail

CommandDoes
lat mail test <address>Sends the built-in test template to the address through [mail].

API Reference

Every public type, function and trait carries doc comments.

cargo doc --workspace --no-deps --open