rust
54 lines · 8 steps
Building an HTMX-aware toggle handler in Axum
An Axum handler flips a todo's completed state in Postgres and returns either an HTML fragment or a full page depending on the caller.
Explained by
highlit
1use axum::{
2 extract::{Path, State},
3 http::HeaderMap,
4 response::{Html, IntoResponse},
5};
6
7pub async fn toggle_todo(
8 State(pool): State<PgPool>,
9 headers: HeaderMap,
10 Path(id): Path<i64>,
11) -> Result<impl IntoResponse, AppError> {
12 let todo = sqlx::query_as!(
13 Todo,
14 r#"
15 UPDATE todos
16 SET completed = NOT completed, updated_at = now()
17 WHERE id = $1
18 RETURNING id, title, completed
19 "#,
20 id
21 )
22 .fetch_one(&pool)
23 .await?;
24
25 let is_htmx = headers
26 .get("HX-Request")
27 .map(|v| v == "true")
28 .unwrap_or(false);
29
30 if is_htmx {
31 return Ok(Html(render_todo_row(&todo)));
32 }
33
34 let remaining = sqlx::query_scalar!("SELECT count(*) FROM todos WHERE NOT completed")
35 .fetch_one(&pool)
36 .await?
37 .unwrap_or(0);
38
39 Ok(Html(render_full_page(&todo, remaining)))
40}
41
42fn render_todo_row(todo: &Todo) -> String {
43 let checked = if todo.completed { "checked" } else { "" };
44 format!(
45 r#"<li id="todo-{id}" class="todo {class}">
46 <input type="checkbox" hx-post="/todos/{id}/toggle" hx-target="#todo-{id}" hx-swap="outerHTML" {checked}>
47 <span>{title}</span>
48</li>"#,
49 id = todo.id,
50 class = if todo.completed { "done" } else { "" },
51 title = askama_escape::escape(&todo.title, askama_escape::Html),
52 checked = checked,
53 )
54}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Axum extractors let you declare exactly which parts of a request a handler needs, right in the signature.
- 2Inspecting a request header lets one endpoint serve both progressive-enhancement fragments and full pages.
- 3Compile-time-checked SQL macros keep the UPDATE and its returned struct in sync with the database schema.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-an-htmx-aware-toggle-handler-in-axum-explained-rust-f6fc/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.