Build the interface where you build the routes

Fourteen lessons in three stages. 01–05 are enough to build a screen: the wiring, what htmx sends, and the partial a page and its swaps share. 06–10 are for a page where one action updates several regions. 11–14 cover messages, rejected forms, rebranding and fjkit check, and can be read in any order. Every demo below runs a real htmx request.

01

Wiring: config, mount, render

Everything else you write is your app, not your front end.

A fjkit app touches the kit in exactly three places. FjkitConfig holds every setting. mount_fjkit() serves the stylesheet and the vendored JS straight out of the installed package, and builds the Jinja environment once per process. @render names the template a route answers with.

The four files below are a complete app. examples/fjkit-demo is the same four files with more pages.


          

base.html is four blocks long because ui/shell.html, which it extends, provides the rest. The diagram below shows it.

An app with its own scripts or images sets FjkitConfig(static_dir=APP_DIR / "static"). mount_fjkit() serves that directory at /static (static_dir_url moves it), and a template links a file with {{ app_static("js/marking.js") }}. The URL carries ?v=<mtime>, the stamp fjkit_static puts on the kit's own assets. StaticFiles sends no Cache-Control, so without the stamp a browser may keep an old copy after a deploy. Do not link app assets with url_for(request, "static", path=…): that URL has no stamp, so a browser can load the new kit and plugin assets together with an old app script. The mount keeps the name "static", so such calls still resolve during a migration. The kit refuses to start when the directory is missing, or when its URL overlaps the kit's mount or a plugin's.

ui/shell.html, drawn

Override a block by naming it in your base.html. Every block is listed on the Cheatsheet.

ui/shell.html — every page extends this <head> <title>{% block title %} · {% block site_title %} theme flash-guard — sets .dark before the first paint dist/fjkit-<style>.css · vendor/htmx · vendor/basecoat · js/errors.js {% block stylesheets %} {% block head %} — your own stylesheet and meta tags <body> {% block sidebar %} empty by default. fill it and the shell grows a side column. <div> — the content column <header> {% block brand %} {% block nav %} {% block header_actions %} <main> — {% block content %} your page — the only block most pages fill <footer> — {% block footer %} {% block toasts %} — always rendered, so a swap can still raise a message

The rest of this page uses four terms in the sense defined here.

Terms

markup

HTML text — what a template produces before a browser parses it, like <div id="board">…</div>. When a later lesson says a route "has markup waiting", it means a template is ready to turn the handler's return value into HTML rather than into JSON

the shell

ui/shell.html, the figure above: the document around your page — <head>, header, <main>, footer, toaster

a fragment

a piece of HTML that is not a whole document: no <!doctype>, no <head>, just the elements. It is what an htmx response carries

a partial

the template that renders a fragment. Its file name starts with an underscore, it never extends the shell, and the page and the htmx endpoints both use it — lesson 05


02 htmx

The htmx request and response

The server answers a swap with HTML. Nothing is serialised for it, and there is no client-side state to keep in sync.

An element names the request to make and where to put the answer. The server answers with a piece of HTML — the same markup it would have put in the page — and htmx drops that piece into the element you named.

One round trip

The only thing that changes on the client is the subtree named by hx-target.

BROWSER <button hx-post> the trigger — a click #board hx-target — the element that gets replaced POST /tasks HX-Request: true HX-Target: board title=Ship+it (form body) FASTAPI router.py service — the real work tasks/_board.html the same partial the page embeds 200 text/html <div id="board">…</div> — a fragment, not a page swap: outerHTML

Try it

The exchange below is a genuine htmx request.

idle

Those HX-* headers are how a route tells a swap from a full page load. Everything else is an ordinary POST. There is no client framework on either side.


03 htmx

hx-target and hx-swap

Two attributes decide everything: which element, and how htmx replaces it.

hx-target picks the element. hx-swap says what to do with it. Every combination below runs a real request against a live board and swaps the real response.

outerHTML replaces the target itself, so the response has to include the wrapper. innerHTML, the default, replaces what is inside it, so the response must not include the wrapper. Mixing the two up gives you a board inside a board.

The board

The template behind it


      

04 htmx

hx-trigger: typing, scrolling, polling

Sensible defaults, and one attribute for everything else.

You usually write no trigger at all. A button fires on click, a form on submit, an input or select on change. hx-trigger is for the other cases. It gives you search-as-you-type, lazy loading and polling with no JavaScript. All three below are live.

keyup changed delay:400ms

changed skips the request when the value did not change; delay:400ms restarts the countdown on every keystroke.

searching…

revealed — load when scrolled into view

Same idea as an image's loading="lazy", except the thing deferred is a rendered fragment.

every 2s — polling

Polling stops when the element is removed. For anything chattier — a reply arriving word by word — load sse_scripts() and return fjkit.sse.events() from an async route; it always ends with the done event sse-close waits for.

Build status, refreshed by the server.


05 htmx

Partials: one file, page and swap

The page embeds the fragment the htmx endpoint returns — so they cannot drift.

A partial is any template whose name starts with an underscore. It never extends the shell, it declares its own imports, and it wraps itself in the element the swap replaces. The full page {% include %}s it; every htmx endpoint returns it bare.

That is why a fjkit app has no "update the row" code path. Every mutation re-renders the whole board partial and swaps it. One definition of what a board looks like, used by the first paint and by every request after it. The working files are in examples/fjkit-demo/app/templates/tasks/.

Request


        

Both handlers name the same file. _board.html is not one task. It is the entire board — the create form, the filter bar, the stats card and every row in the table, wrapped in the one <div id="board"> that every control on the page targets. The leading underscore means "not a page", not "small".

So a click on Advance in row three sends one POST, and what comes back is the board with all eight rows re-rendered, one of them now saying Doing. That is the trade fjkit makes. You render more HTML than strictly changed, and in exchange there is exactly one definition of what a board looks like. Below are the three files, and every htmx attribute in them.

{# tasks/page.html — answers the full GET #}
{% extends "base.html" %}
{% from "ui/layout.html" import page_header %}

{% block content %}
  {{ page_header("Tasks", "Every control here swaps #board.") }}

  {# The first paint. This is the same file POST /tasks answers with. #}
  {% include "tasks/_board.html" %}
{% endblock %}
Extends the shell, writes a heading, and includes the partial. Nothing about the board is described twice.
{# tasks/_board.html — the whole board: create form, filters, stats, every row #}
{% from "ui/button.html" import button, button_group %}
{% from "ui/table.html" import table %}
{% from "tasks/macros.html" import task_row, TASK_COLUMNS %}

{# The wrapper is inside the file, because hx-swap="outerHTML" replaces it. #}
<div id="board">

  {% include "tasks/_new_task.html" %}

  {# The filter bar. Each button re-fetches the board with a query string. #}
  {% call button_group() %}
    {% for value, label in status_filters %}
      {{ button(label, size="xs",
                hx_get=url_for(request, "tasks_board") ~ ("?status=" ~ value if value else ""),
                hx_target="#board", hx_swap="outerHTML") }}
    {% endfor %}
  {% endcall %}

  {% call table(TASK_COLUMNS, rows=tasks) %}
    {# A repeated element is a macro, not an include in a loop. #}
    {% for task in tasks %}{{ task_row(request, task, filter_query) }}{% endfor %}
  {% endcall %}

</div>
No extends and no doctype, so this renders standalone — which is what lets an htmx endpoint return it bare.
{# tasks/macros.html — one row, and the htmx that fires from it #}
{% macro task_row(request, task, filter_query="") %}
  <tr>
    {{ cell(task.title, tone="strong") }}
    {{ cell(badge(task.status.value | capitalize, variant=task.status_variant)) }}
    {% call row_actions() %}
      {# Advance one task — and get the whole board back. #}
      {{ button("Advance", variant="ghost", size="xs",
                hx_post=url_for(request, "tasks_advance", task_id=task.id) ~ filter_query,
                hx_target="#board", hx_swap="outerHTML",
                hx_disabled_elt="this") }}
      {{ button("", variant="ghost", size="icon-xs", icon_name="trash",
                aria_label="Delete " ~ task.title,
                hx_delete=url_for(request, "tasks_delete", task_id=task.id) ~ filter_query,
                hx_target="#board", hx_swap="outerHTML",
                hx_confirm="Delete this task?") }}
    {% endcall %}
  </tr>
{% endmacro %}
The row is a macro, and it is where the htmx lives: every action points at #board and swaps outerHTML, so the reply is always the whole partial.

Why one file covers both

it is the board, not a row

_board.html renders the form, the filters, the stats and all the rows. A single task is task_row() in macros.html — a macro, because a repeated element is a macro and a partial is what a request answers with

the wrapper is in the file

the first line of the partial is <div id="board">. It has to be, because every control says hx-swap="outerHTML". That swap replaces the wrapper itself, so the reply has to bring one back

one context, built once

both callers need the identical names in the context — tasks, stats, status_filters. The router builds them once, in board(), and both handlers return it

every action carries the filter

every row action carries filter_query, so advancing a task while the board is filtered to Doing answers with the board still filtered to Doing

What it costs

bytes on the wire

the whole board, every time. That is a few kilobytes of HTML the browser parses instead of a diff it does not have to compute — and no client-side model to keep in step

when it stops paying

when a board grows past what you want to re-render, the answer is a smaller partial with its own id, not a smarter client. Lesson 06 and lesson 07 are both that answer

focus

an outerHTML swap replaces the element the focused input is inside. htmx restores focus by id, so give an input that survives a swap a stable id

big boards

templates.page() renders this. Reach for templates.stream() only when the row count is the user's to choose

The board, live — add, advance, delete

Every control targets #demo-board, and every response is the whole board partial.

working…

Traps worth knowing

full page back

returning page.html from an htmx route nests a whole document inside your div — return the partial

4xx does not swap

htmx ignores error responses by default. The shell adds 422, and only 422, which is what lets a rejected form come back as the form itself

lost wrapper

outerHTML needs the wrapper in the response, or the target disappears

stale filter

a row action must carry the active filter, or the swap silently resets the view

inherited swap

hx-target and hx-swap are inherited from ancestors. A button inside a card that polls itself with outerHTML inherits that swap, and replaces the element it meant to fill — spell both out on any trigger nested inside another htmx element

Server-side helpers

HX-Request

the header that tells a route it is answering a swap

HX-Trigger

response header that fires a client event — how fjkit raises a toast from a swap, which has no toaster in it

HX-Redirect

full-page redirect from inside a swap response

hx-swap-oob

one response, several regions — the next lesson


06 htmx

One reply, many regions: hx-swap-oob

hx-target names one element. When one answer has to move six, the other five carry their own address.

Every swap so far has had one target, and that is enough while the things that change sit under one element. The board is a single <div id="board">: every control on it points there, and every response is the whole board.

A search result is not one thing. One query moves a row of counters above the table, the table itself, a progress card, a facet list and a siblings panel in the aside, and a detail panel below it — six fragments in three places, and the only element that contains all six is <body>. Swapping the body is a page reload with extra steps.

So the reply carries the other five out of band — outside the one channel hx-target describes. Each of them says where it belongs by carrying the id it is going to.

The trigger is ordinary: one input, one hx-get, one hx-target — the same shape as lesson 03. It names #search-matches and knows about no other region on the page.

{# search/page.html — the one control that starts all of this #}
{% call form(action=url_for(request, "search_page"), method="get") %}
  {% call field_row("field-and-button") %}
    {{ text_field("q", label="Search tasks", value=query, type="search",
                  hx_get=url_for(request, "search_page"),
                  hx_trigger="input changed delay:250ms, search",
                  hx_target="#search-matches", hx_swap="outerHTML",
                  hx_push_url="true", hx_indicator="#search-busy") }}
    {{ button("Search", variant="primary", type="submit", icon_name="search") }}
  {% endcall %}
{% endcall %}
hx_* keywords on any fjkit macro become hx-* attributes on the element it emits. The form around it carries action and method, so the same query still works with scripting off.
<input class="input" type="search" name="q" id="q"
       hx-get="/search"
       hx-trigger="input changed delay:250ms, search"
       hx-target="#search-matches"
       hx-swap="outerHTML"
       hx-push-url="true"
       hx-indicator="#search-busy">
One target. htmx will replace #search-matches with whatever comes back — and it does not know the reply is about to move five other elements.

What comes back from one keystroke

GET /search?q=cache, answered by one handler and one response model.

<div id="search-matches">…</div>                     ← no marker: this is what hx-target gets
<div id="search-stats"    hx-swap-oob="true">…</div>   ← replaces the counters
<div id="search-progress" hx-swap-oob="true">…</div>   ← replaces the progress card
<div id="search-facets"   hx-swap-oob="true">…</div>   ← replaces the facet list
<div id="search-related"  hx-swap-oob="true">…</div>   ← replaces the siblings panel
<div id="search-detail"   hx-swap-oob="true">…</div>   ← replaces the detail panel

What htmx does, in order

1 — lift

htmx lifts every top-level element carrying hx-swap-oob out of the response

2 — place

it matches each one to the element on the page with the same id, and replaces it

3 — then the target

it swaps whatever is left into hx-target as usual

Four things to know

the value

true replaces the matching element; innerHTML, beforeend and the rest of the swap vocabulary all work here too

it fails in silence

htmx drops an id that matches nothing without a word — no error, no console entry, and that region keeps the previous query's numbers

top level only

an out-of-band fragment nested inside a wrapper is not one — which is why the reply template is a flat list of includes

not the target

never mark the fragment that hx-target names. htmx would lift it out too, and swap the target with nothing

On the fjkit side there is no new machinery. The page and the reply {% include %} the same six partials and differ in one variable. The page renders them without the out-of-band flag, and the reply renders them with it. Each partial defaults the flag itself, so it still renders standalone.

One set of partials, two ways of rendering them

{# _results.html — what an htmx request gets #}
{% include "search/_matches.html" %}
{% with oob = true %}
  {% include "search/_stats.html" %}
  {% include "search/_progress.html" %}
  {% include "search/_facets.html" %}
  {% include "search/_detail.html" %}
  {% include "search/_related.html" %}
{% endwith %}

{# _stats.html — and every other region, at the top #}
{% set oob = oob | default(false) %}
<div id="search-stats"{% if oob %} hx-swap-oob="true"{% endif %}>
  …
</div>

The page decides where a fragment lives, once. Move the facet card from the aside into the main column and the router, the response model and the swap are all unchanged. The working files are in examples/fjkit-demo/app/templates/search/. Lesson 07 covers the other half of the same page.


07 htmx

One id, many fragments: HX-Trigger

The opposite problem to lesson 06. The trigger produces an id, and each region has a different question to ask with it.

The last lesson worked because one handler could answer every region at once: one query, six fragments, one response model holding all of them. Opening a row on that same page is a different shape. The click produces an id, and the panels that care about it each need their own query — the detail of that task, the other tasks its owner has. A handler answering all of them would have to import every service on the page, and a third panel would mean editing it.

So the pick answers with its own region — the table, with the row now marked — and sends the id out in HX-Trigger. htmx raises that header as a DOM event, and the fragments that care listen for it and fetch their own data. The route does not know how many of them there are, or that any of them exist. Adding a panel is one more subscriber and no change to any route.

The route that picks

A GET, because picking changes nothing on the server. The table is the button's hx-target, so the reply swaps it in band.

@router.get("/search/select/{task_id}", name="search_select")
@render("search/_matches.html",
        hx_trigger=lambda task_id: {"task-selected": {"task_id": task_id}})
def select_task(service: ServiceDep, task_id: int, q: str = "") -> MatchesResponse:
    """Mark the row, answer with the table, and tell the panels which id."""
    return _matches(service, q, _selected(service, task_id).id)

hx_trigger declares the event. It is a parameter of @render rather than a header the handler writes, so it works the same on a route that also renders. A callable is resolved per request from the handler's own parameters by name — task_id here — plus result, what the handler returned. Returning None from it is not an error, so a route can broadcast only sometimes.

Nothing else about that route is special. It is an ordinary partial route — one template, one response model — with an event attached, and that is what makes the pattern cheap. The swap and the broadcast are one round trip, declared in one place.

A second action on the same page shows the other half. Advance changes a status, so it raises a different event, and a different set of fragments cares.

A second event, from a route that changes something

The reply is the swap — the detail panel is this button's hx-target — and the header is what the other four hear.

@router.post("/search/advance/{task_id}", name="search_advance")
@render("search/_detail.html",
        hx_trigger=lambda task_id: {"task-changed": {"task_id": task_id}})
def advance_task(service: ServiceDep, task_id: int) -> DetailResponse:
    """Advance the task, answer with the detail panel, and say what changed."""
    if service.advance(task_id) is None:
        raise HTTPException(status_code=404, detail="task not found")
    return DetailResponse(selected=service.get(task_id))

Two events, and each fragment hears the ones it has a reason to. The counters listen for task-changed and not task-selected, because picking a task changes no count. The facets listen for neither, because advancing one changes no owner and no priority. Which broadcasts a fragment hears is the fragment's own decision, and no route knows it exists.

Who hears what

Fragment task-selected task-changed Why
the results table no yes it is the pick reply's own target; an advance changes what a row says
the detail panel yes no it is the advance reply's own target — hearing that event would loop
the siblings panel yes yes whose siblings these are, and what their status is
the counters, the progress card no yes a pick changes no count; an advance does
the facets no no no facet on that card is about a status

One rule holds this together: the fragment a route answers with must not subscribe to the event that route raises. The route is already replacing it in band, so hearing the event fetches it a second time for the same click. On a fragment that is its own target, that never stops. htmx does not catch it, because a subscriber asking for its own URL is what the attribute says to do. So the table hears only task-changed and the detail panel only task-selected. Each is a route's target for one event and a subscriber for the other, never both for the same one.

The subscriber

These attributes on every region that cares, and nothing on the ones that do not.

{# a panel that needs only the id #}
<div id="search-detail"
     hx-get="/search/detail"
     hx-trigger="task-selected from:body"
     hx-vals="js:{task_id: event.detail.task_id}"
     hx-target="this" hx-swap="outerHTML">…</div>

{# a region that also depends on the search box #}
<div id="search-stats"
     hx-get="/search/stats"
     hx-trigger="task-changed from:body"
     hx-include="[name='q']"
     hx-target="this" hx-swap="outerHTML">…</div>

The attributes that matter

who is listening

from:body — htmx raises the event on the element that made the request, and it bubbles. The panels are nowhere near that element, so they listen where it arrives

how the id arrives

hx-vals="js:…" is the one place the id turns back into a query parameter. Reading it out of the event, rather than remembering the selection on the server, keeps the endpoints stateless and two open tabs independent

what else it needs

hx-include — for what the event does not carry. The counters count the matches, so they need the search box as well as the id, and a selector fetches it off the page instead of every event carrying it

what gets replaced

hx-target="this" — every subscriber replaces itself, so a reply is always one region and the sender never has to know how many regions exist

Four things to know

send an object

the trigger value must be a JSON object. htmx passes an object through as event.detail and wraps anything else — an array included — as {value: …}, so a listener reading event.detail.task_id finds nothing

it fires before the swap

HX-Trigger fires before the swap, which is why the id travels in the event: a hidden input holding the selection would still hold the old one when the subscribers read it. HX-Trigger-After-Swap is the header for the other order

inherited hx-vals

hx-vals is inherited, and htmx merges it up the tree on a path that does not consult hx-disinherit. An htmx element inside a subscriber — the row's own title, which is the button that opens it — has to say hx-vals="unset", which is the only value that stops the walk

N panels, N requests

N subscribers is N requests. The page makes those requests instead of the handler making all the queries, so reach for hx-sync or a cache when the queries are expensive

The two lessons do not compete, and the demo does not put them on separate pages. They answer different questions, and /search asks both: a query is one question the server can answer completely, and a pick is an id that three regions each have a different question about.

Which one a page needs

Ask hx-swap-oob HX-Trigger
what produces the change one query the server can answer for every region an id each region has a different question about
who knows the regions the handler — it renders all of them nobody; each region declares itself
requests per interaction 1 1 + one per subscriber
adding a region edit the handler, the model and the reply template one more subscriber; nothing else changes

The working files are app/routers/search.py and app/templates/search/ in the demo — the same page as lesson 06. Every region there carries a render stamp, so the page itself shows which regions an action reached, with no network tab. A query is one request and six new stamps. A pick is three requests and three stamps — the table, the detail panel, the siblings panel — while the counters, the progress card and the facets sit still. An advance is five, and the facets are then the only card that does not move.


08 htmx

Page state: where the selected id lives

The last lesson moved an id between regions. This one asks where that id lives when the page is reloaded.

A pick drives four regions. After a reload, all four have to show the same task again, so the id needs a place that outlives the request.

The state the server reads to answer — which record, which page, which sort column — goes in the URL, as a path segment or a query parameter, because that is the one place a reload, a bookmark, the back button and a link sent to a colleague can all read it. The page route takes it as an ordinary parameter and every sub-request inside the region carries it too — in its own path, or through hx-vals and hx-include, both of which htmx inherits from the region root, so it is written once.

The two halves that make a pick survive a reload

The page route reads the id the pick pushed. Neither half is any use without the other.

@router.get("/panels", name="panels_page")
@render("panels/page.html", partial="panels/_matches.html")
def panels_page(service: ServiceDep, task_id: int | None = None) -> MatchesResponse:
    """The page, and the table it swaps. The pick is a parameter, not a session."""
    return _matches(service, _selected(service, task_id).id if task_id else None)


@router.get("/panels/select/{task_id}", name="panels_select")
@render("panels/_matches.html", hx_trigger_after_swap=SELECTED_EVENT)
def select_task(request: Request, response: Response, service: ServiceDep, task_id: int) -> MatchesResponse:
    """Mark the row, put the pick in the address bar, then announce it."""
    selected = _selected(service, task_id)
    htmx.push_url(response, _page_url(request, selected.id))
    return _matches(service, selected.id)

htmx.push_url writes HX-Push-Url, which puts a swap in the address bar and in history. It is for the swap that changes what the page is looking at, not for every swap. Push on an edit and the back button sends the visitor back through their own edits. Where the request URL is already the one to show, hx-push-url="true" on the trigger says the same thing with no header. What must hold either way is that the pushed URL is one the app answers with a whole page. A URL the app cannot render is worse than no URL at all.

The working files are app/routers/panels.py and app/templates/panels/ in the demo. Pick a row and watch the address bar; reload, and the same task is open with the same panel showing. Open a second tab on a different task and neither one moves the other.


09 htmx

While the request is in flight

A swap is a round trip, and nothing stops a second click during it. Two attributes cover the whole of the wait.

htmx adds the class htmx-request to an element for the length of a request and removes it afterwards. Without hx-indicator that element is the one that fired the request; with it, it is whatever the selector names. Then this stylesheet — htmx's own, injected at startup — does the rest:

The rules htmx injects

Two selectors, comma separated.

.htmx-indicator { opacity: 0; visibility: hidden }

.htmx-request .htmx-indicator,
.htmx-request.htmx-indicator { opacity: 1; visibility: visible; transition: opacity 200ms ease-in }

The first selector covers an indicator inside the marked element — a spinner in the button that was clicked. The second covers an indicator that is itself the marked element, which is the shape fjkit uses: spinner(indicator=true) adds htmx-indicator and nothing else, so a loading state costs you no CSS, no JavaScript and no round trip to reveal it.

Both attributes, on one form

examples/fjkit-demo/app/templates/jobs/page.html

{% call form(action=url_for(request, "jobs_start"), target="#job-list",
             hx_indicator="#job-busy",
             hx_disabled_elt="find button[type=submit]") %}
  {% call field_row("field-and-button") %}
    {{ select_field("kind", label="Background job", options=kind_options) }}
    {% call row(gap=2) %}
      {{ button("Start", variant="primary", type="submit", icon_name="play") }}
      {{ spinner(indicator=true, id="job-busy", label="Starting the job") }}
    {% endcall %}
  {% endcall %}
{% endcall %}

hx-disabled-elt is the same machinery aimed at a different problem. It sets disabled on whatever the selector names for the length of the request and clears it after, which is what stops a double click from advancing a task twice or posting two of the same form. The selector takes this, a find …/closest … relative form, or an ordinary CSS selector.

How they behave

counted

both are counted, not toggled — htmx keeps a request count per element, so an early reply cannot re-enable a control another request is still using

no layout shift

the indicator is hidden with visibility and opacity, never display — it holds its space, so nothing on the page jumps when it appears

inherited

both are inherited: put hx-indicator on a container and everything inside it shares one spinner. this and inherit are valid values

a bad selector warns

a selector that matches nothing does warn here — The selector "…" returned no matches! — unlike an out-of-band id, which fails silently

Traps worth knowing

not inside the target

keep the indicator outside the target. A swap removes an element inside the target mid-request, and its id with it

the default

with no hx-indicator at all the class lands on the trigger itself, so .htmx-request styling on a button is the cheapest loading state there is

already-disabled controls

htmx marks what it disabled with data-disabled-by-htmx, so a control that was already disabled stays disabled afterwards

a fast request

expect some indicators to barely flash. That is the request being fast, not the indicator being broken — the jobs page does its work after the response, which is why the card polls


10 htmx

Nine htmx patterns, and their handlers

Screens differ; the shapes do not. Each one is a trigger, a target and a partial.

The whole attribute vocabulary fits on one screen, and the Cheatsheet page prints it. What takes longer to learn is the handful of arrangements it keeps forming. Here they are in the fjkit spelling: the macro call on one tab, the handler that answers it on the other.

Every handler below returns a partial and is a plain def, so Starlette runs it in the threadpool. Each pattern links out to the htmx page it comes from. The upstream docs and attribute reference are short enough to read whole, and worth reading whole.

Pattern


              

What they have in common

one partial

the page includes it, the endpoint returns it — never two renderings of the same fragment

no client state

the cursor, the filter and the edit mode all live in the URL or in which partial is on screen

state in the URL

anything a reload has to survive is a query string a full GET can answer

degrades

drop the hx-* keywords and the same macros emit a form and links that still work

Not yet, on purpose

dialogs

hx-confirm until then — it is the browser's own, and it works

sorting

a filter bar with different query params until the table macro supports it


11 fjkit.messages

Messages: three layers

One message, three layers — and only the top one needs a secret.

Showing a line of text to the person who made this request is not one feature but three, stacked: the region that draws it, the way it gets onto a response, and the way it survives a redirect. Only the last needs a signing secret, which is why one of them is a plugin and the other two are not.

The three layers

Two of them are core, because neither of them needs anything from you.

Layer Where it lives Core or plugin
the region ui/feedback.html's toaster region, drawn by ui/shell.html on every page whether or not anything is in it core
onto this response fjkit.messages — messages.add(request, …), from a route, a service or an exception handler core
past a redirect fjkit.flash — a short-lived signed cookie, a plugin on the Plugins page plugin
from fjkit import messages

messages.add(request, "Saved", category="success")
messages.add(request, "Could not save", "The title is required.", category="error")

No plugin, no secret, no configuration — which is the point of drawing the line here. Signing a cookie needs a secret, and requiring one from every app, including one with no forms and nothing to say, would stop mount_fjkit(app) from working with no config at all. Everything that does not need a secret is core.

The third layer is not a superset of the second either. A redirect replaces the page, so the document that would have shown the message is gone before the response arrives, and a cookie is the only thing that crosses. On a response that is not a redirect, that same cookie is a round trip for a message about to be rendered anyway. So the two are layered rather than merged. FlashPlugin queues into fjkit.messages, and the shell has one loop instead of one per delivery mechanism.

How it reaches the browser

@render picks the channel. The caller never has to know which.

What the response is The channel What draws it
a full page render the context the shell's toaster region, straight into the markup
a fragment, an htmx swap HX-Trigger the shell's listener, which turns the event back into a toast

A header rather than markup, because a fragment has no toaster in it. An htmx swap replaces one region, and the region a toast belongs in is elsewhere on the page. It also works on a response htmx will not swap at all. htmx reads HX-Trigger in handleAjaxResponse before it consults responseHandling for the status code, so a 422 or a 500 can still raise a toast on the page the person is looking at.

Worth knowing

fjkit_messages() is a global, not a context key

so a route passes nothing in, and a page that has never heard of messages still shows one

consumed by being iterated

a template that loops over the queue marks it delivered; asking whether there is anything to show does not, because that is not showing it. The flash plugin depends on the distinction

HX-Trigger is merged, not replaced

a handler that set an event of its own keeps it — dropping it because a toast happened to be queued is a bug that only appears when both are in play

category

info, success, warning, error — a meaning, not a colour. toast() maps each to an icon and a timeout and fjkit.css maps each to a role token, so "error is red" is decided once and survives a rebrand


12 fjkit.errors

When a form is rejected

A rejected form shows each message under its field. No route has to handle the rejection.

FastAPI answers a rejected form with {"detail":[{"type":"missing",…}]} and a 422. For an API that is right. For a page it is nothing: htmx does not swap a 4xx, so the person filling the form watches nothing happen, and a plain POST lands them on a screen of JSON.

The fix is to notice what that reply already is. It names every field that failed, under the string the form posted it as, with a message a person can read — and the form is still on the page, with everything the person typed still in its controls. Nothing has to be rendered again, remembered, or rebuilt. So mount_fjkit() sends the 422 back as it is, and one script the shell loads, js/errors.js, writes each message under its field. Every handler keeps the signature FastAPI wrote for it, and no route names a template for its rejected state, because there is nothing to render.

What each caller gets

The same question @render asks about the wire, asked about a submit that was refused.

Who asked Answer Why
htmx FastAPI's 422, drawn by the page the form is still there; the script writes each message under the control its loc names, and what was typed stays put
a browser navigation 422 and a page a plain <form method="post"> has left the page, so errors/page.html is rendered through your own shell
a script, curl, a service FastAPI's own reply — byte for byte, with the status it always had. The same bytes as the first row; only the reader differs

A caller that did not ask for markup keeps {"detail": …}, because turning an API's error into an HTML page would be a worse bug than the one this fixes. The first row is the same bytes, which is the whole design. An endpoint that is also somebody's API has one error contract, and the page reads it the way any other client would.

That asks one thing of a route, and it is what FastAPI already asks:

@router.post("/tasks", name="tasks_create")
@render("tasks/_board.html")
def create_task(service: ServiceDep, payload: TaskCreate) -> BoardResponse:
    service.create(payload)
    return _board(service)
The model is the signature. Its fields, its limits and its OpenAPI schema are one declaration, and a rejected one is FastAPI's to report — under body, with the field's name.
{% call form(action=url_for(request, "tasks_create"), target="#board",
             reset_on_success=true, encoding="json", id="new-task") %}
  {{ text_field("title", label="New task", required=true) }}
  {{ select_field("priority", label="Priority", options=priority_options,
                  selected="normal") }}
{% endcall %}
One form, written once, with nothing about errors in it. The script finds each control by name and the paragraph under it by aria-describedby — the wiring every field macro already does.

Keeping what was typed costs nothing, because nothing touches it. The old answer to a 422 was to render the form again with the values echoed back, and it worked until a field held more than one value, or the form needed something only the handler that never ran could have built. Both problems disappear when the form is not rendered again.

A message with no field to land on — a whole-model rule, a body that could not be parsed, a bad path segment — becomes a toast, through the event fjkit.messages uses. The next request from the same form clears what the last one said, so an accepted resubmit leaves no stale rejection on screen.

The rest of the error handling

a ValidationError your own code raised

left to propagate, on purpose. It has the same shape as a rejected form and is not one. It is equally what Task(**row) failing three layers down in a service looks like, and drawing a bug as a friendly message hides it behind an apology about a field nobody filled in. Declare the model in the signature and FastAPI raises the request-scoped error that is handled

catch_unexpected_errors

off by default, and that default is the useful one. In development a traceback in the terminal beats a tidy apology in the browser. FjkitConfig.for_production() turns it on, with the other two dev-only settings. The 422 handler is installed either way, because a rejected form is not a bug

unexpected_error

the words that toast says. Leave it and the kit says <em>Something went wrong</em>; set a <code>Message</code> to change them once, or a callable <code>(request, exc) -&gt; Message</code> to pick them per exception. Choose the words from the exception — never put <code>str(exc)</code> in them, that is the inside of your app

a 404

an unknown address, or a route that raised <code>HTTPException(404)</code>. A navigation gets errors/page.html, which says the page may have moved. An htmx swap gets an empty 404 and a toast, so the page it came from stays as it was. A JSON client gets FastAPI's own reply. Every other <code>HTTPException</code> is FastAPI's reply, headers included. Register your own <code>HTTPException</code> handler after <code>mount_fjkit()</code> and it replaces this one

not_found_error

the words of that 404 toast, taking the same <code>Message</code> or callable as <code>unexpected_error</code>. Leave it and the kit says <em>That could not be found</em>

your own handlers

a 404, a <code>RequestValidationError</code> or an <code>Exception</code>/500 handler you registered before <code>mount_fjkit()</code> is kept; one registered after it replaces the kit's. When the error page itself cannot render because a plugin raised what a route would have — the auth plugin's 503 during an outage — the visitor gets that handler's answer

errors/page.html

the page a failed navigation lands on. Replace it by writing a file at the same path in your own template directory — the same shadowing fjkit eject uses, so there is no separate custom-error-page mechanism to learn

js/errors.js

the third and last file every page loads, after htmx and Basecoat. It listens to htmx:beforeSwap, so a 422 that is not FastAPI's list — a route answering with markup of its own — is left alone


13 theming

Rebranding: brand and status tokens

Rebranding is a CSS variable. "Green means done" is not one of the things it changes.

Drag the hue. You are editing --primary on :root, which is the same three lines an app writes in its own stylesheet. There is no build step in between. The whole page moves, including this sidebar and these cards, because the page is built on the same tokens.

Watch the status badges. They do not move. Status colour is deliberately not wired to the brand, because "green means done" has to survive a rebrand.

The Scheme buttons are the visitor's choice, and by default the visitor keeps it: FjkitConfig(color_scheme="system") follows their saved choice, then their OS, and puts a toggle in the header. An app that is only ever light or only ever dark says color_scheme="light" or "dark". The server then renders the scheme on <html>, the shell leaves out the toggle and the pre-paint script, and nothing reads a choice the visitor saved earlier. theme_toggle() renders nothing under a fixed scheme, so an app that fills header_actions itself calls it as before.

The three lines you would write

Presets
Scheme

The page, repainted

Your whole rebranding procedure


      
A stylesheet loaded after fjkit's. No Tailwind config, no rebuild, no watcher.

Tied to the brand hue

primary

brand fill, plus ring for focus

primary-foreground

text on a brand fill — never an absolute white

background · card

page ground and surfaces, tinted toward the brand

muted · border

quiet surfaces, hairlines, secondary text

Not tied to it, on purpose

success

done, passing, healthy

warning

needs attention, not yet broken

info

in progress, neutral notice

destructive

delete, fail, irreversible


14

fjkit check: the closed vocabulary

A convention nobody can violate by accident is worth more than one written down.

fjkit check reads your templates and rejects two things: colour literals, and any class outside the component vocabulary. It rejects a utility even when it works today. An app leaning on a spacing utility because fjkit's shell happens to emit it breaks silently the day the shell stops.

Edit the markup. The checker below runs fjkit's own rules against its real class list — … — and it is the code that runs in CI and over this site's templates.

app/templates/tasks/_board.html

A blocked class is information. It names the component or the parameter that does not exist yet. Open an issue with the class it blocked.

Commands

fastapi dev

run the app — nothing to rebuild alongside it

fjkit check

every class is part of the vocabulary

fjkit eject

an escape hatch. Take one macro into your app, and its file's other macros stay the kit's

fjkit build-css

fjkit's own release step, never yours