ilek

Axum + HTMX in Rust: build an interactive app with ilek

ilek is a Rust view layer for server-driven UIs, built on axum, Maud, and htmx. Your handlers stay ordinary axum handlers: they render HTML with Maud, and htmx updates the page without a full reload.

You'll build the counter example from a static page to an interactive app. Each click sends a POST request, and the server returns HTML to update the count and heading. Typed actions connect the buttons to handlers; fragments identify the elements to replace.

Create the project#

Requires Rust 1.97+.

cargo new --bin counter
cd counter
# Cargo.toml
[package]
name = "counter"
version = "0.1.0"
edition = "2024"

[dependencies]
ilek = "0.5"
axum = "0.8"
axum-extra = { version = "0.12", features = ["typed-routing"] }
maud = { version = "0.27", features = ["axum"] }
tokio = { version = "1", features = [
    "macros", "rt-multi-thread", "net",
] }

The macros also need axum-extra and maud as direct dependencies.

Render a page#

// src/main.rs
use axum::Router;
use ilek::{
    RouterExt,
    maud::{DOCTYPE, Markup, html},
    route,
};

#[route("/")]
struct HomePath;

async fn home(_: HomePath) -> Markup {
    html! {
        (DOCTYPE)
        html lang="en" {
            head {
                meta charset="utf-8";
                meta name="viewport"
                    content="width=device-width, initial-scale=1";
                title { "Counter" }
            }
            body {
                main {
                    button { "−" }
                    (counter(0))
                    button { "+" }
                }
            }
        }
    }
}

fn counter(count: i64) -> Markup {
    html! { output id="counter" { (count) } }
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let router = Router::new().view(home);
    let listener =
        tokio::net::TcpListener::bind("127.0.0.1:4002").await?;
    println!("listening on http://127.0.0.1:4002/");
    axum::serve(listener, router).await
}

Maud's html! macro produces Markup. The counter function is ordinary Rust.

#[route("/")] wraps axum-extra's TypedPath derive and typed_path attribute, adding deserialization and markup support.

The view method delegates to typed_get. Its action counterpart registers POST handlers, taking the route from the last argument.

cargo run

Open http://127.0.0.1:4002/. The page shows 0 and two buttons. They don't do anything yet.

Add interactivity#

First, load htmx 4 from a CDN. Add this after the title in the page head:

script
    src="https://cdn.jsdelivr.net/npm/htmx.org@4.0.2/dist/htmx.min.js"
    integrity="sha384-6NzMyCdh08UZ4b4M17SJJKQLdDijx4z2IqqKLKD0Q/PzCFQLpFuk3konY0WgqbTy"
    crossorigin="anonymous"
    defer {}

Add shared state to src/main.rs:

use std::sync::atomic::AtomicI64;

static COUNT: AtomicI64 = AtomicI64::new(0);

The count is shared by all visitors and resets on restart.

Handle a click#

#[action] pairs a typed route with a form-body extractor. Unlike TypedPath, its fields come from the body, not URL captures.

Add the action and its handler:

use std::sync::atomic::Ordering;

use axum::response::IntoResponse;
use ilek::{action, hx::SwapOption, partial};

#[action("/add")]
struct Add {
    by: i64,
}

async fn add(Add { by }: Add) -> impl IntoResponse {
    let count = COUNT.fetch_add(by, Ordering::Relaxed) + by;

    partial! {
        ("#counter", SwapOption::OuterHtml) => counter(count),
    }
}

Axum requires body-consuming extractors last: put Add after other handler arguments, such as State.

The partial! response replaces the whole #counter element with the new markup. The target is a CSS selector.

Connect the buttons#

Replace the page's main block:

main {
    button hx-action=(Add::action().by(-1)) { "−" }
    (counter(COUNT.load(Ordering::Relaxed)))
    button hx-action=(Add::action().by(1)) { "+" }
}

Add::action() supplies the endpoint and POST method; the by setter supplies the form value. It returns a builder with a setter for each field in the Add struct.

For form inputs, name=(Add::FIELD.by) supplies the generated field name.

In main(), replace the router declaration:

let router = Router::new().view(home).action(add);

Restart the app and reload. Both buttons now change the number without reloading the page.

Full code for this stage
// src/main.rs
use std::sync::atomic::{AtomicI64, Ordering};

use axum::{Router, response::IntoResponse};
use ilek::{
    RouterExt, action,
    hx::SwapOption,
    maud::{DOCTYPE, Markup, html},
    partial, route,
};

static COUNT: AtomicI64 = AtomicI64::new(0);

#[route("/")]
struct HomePath;

async fn home(_: HomePath) -> Markup {
    html! {
        (DOCTYPE)
        html lang="en" {
            head {
                meta charset="utf-8";
                meta name="viewport"
                    content="width=device-width, initial-scale=1";
                title { "Counter" }
                script
                    src="https://cdn.jsdelivr.net/npm/htmx.org@4.0.2/dist/htmx.min.js"
                    integrity="sha384-6NzMyCdh08UZ4b4M17SJJKQLdDijx4z2IqqKLKD0Q/PzCFQLpFuk3konY0WgqbTy"
                    crossorigin="anonymous"
                    defer {}
            }
            body {
                main {
                    button hx-action=(Add::action().by(-1)) { "−" }
                    (counter(COUNT.load(Ordering::Relaxed)))
                    button hx-action=(Add::action().by(1)) { "+" }
                }
            }
        }
    }
}

#[action("/add")]
struct Add {
    by: i64,
}

async fn add(Add { by }: Add) -> impl IntoResponse {
    let count = COUNT.fetch_add(by, Ordering::Relaxed) + by;

    partial! {
        ("#counter", SwapOption::OuterHtml) => counter(count),
    }
}

fn counter(count: i64) -> Markup {
    html! { output id="counter" { (count) } }
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let router = Router::new().view(home).action(add);
    let listener =
        tokio::net::TcpListener::bind("127.0.0.1:4002").await?;
    println!("listening on http://127.0.0.1:4002/");
    axum::serve(listener, router).await
}

Run

cargo run

Update fragments#

The response still targets #counter, while the counter function defines id="counter". Rename one without the other and updates break.

A fragment keeps the ID with its markup. Replace counter():

use ilek::fragment;

#[fragment]
fn counter(count: i64) -> Markup {
    html! { output id=(Self) { (count) } }
}

Self supplies the fragment's ID. The function still renders in the page; in a partial response, it carries its target and an outerHTML swap.

Replace add():

async fn add(Add { by }: Add) -> impl IntoResponse {
    let count = COUNT.fetch_add(by, Ordering::Relaxed) + by;

    partial! { counter(count) }
}

Update another element#

Add a heading fragment:

#[fragment]
fn heading(count: i64) -> Markup {
    let title = match count {
        0 => "Zero",
        n if n % 2 == 0 => "Even",
        _ => "Odd",
    };
    html! { h1 id=(Self) { (title) } }
}

In the home handler, read the count before the markup:

let count = COUNT.load(Ordering::Relaxed);

Replace its body block:

body {
    (heading(count))
    main {
        button hx-action=(Add::action().by(-1)) { "−" }
        (counter(count))
        button hx-action=(Add::action().by(1)) { "+" }
    }
}

Return both fragments from the add handler by replacing its partial response:

partial! {
    counter(count),
    heading(count),
}

Restart and reload. Each click updates the count and its Zero / Odd / Even heading in one response.

Full code for this stage
// src/main.rs
use std::sync::atomic::{AtomicI64, Ordering};

use axum::{Router, response::IntoResponse};
use ilek::{
    RouterExt, action, fragment,
    maud::{DOCTYPE, Markup, html},
    partial, route,
};

static COUNT: AtomicI64 = AtomicI64::new(0);

#[route("/")]
struct HomePath;

async fn home(_: HomePath) -> Markup {
    let count = COUNT.load(Ordering::Relaxed);

    html! {
        (DOCTYPE)
        html lang="en" {
            head {
                meta charset="utf-8";
                meta name="viewport"
                    content="width=device-width, initial-scale=1";
                title { "Counter" }
                script
                    src="https://cdn.jsdelivr.net/npm/htmx.org@4.0.2/dist/htmx.min.js"
                    integrity="sha384-6NzMyCdh08UZ4b4M17SJJKQLdDijx4z2IqqKLKD0Q/PzCFQLpFuk3konY0WgqbTy"
                    crossorigin="anonymous"
                    defer {}
            }
            body {
                (heading(count))
                main {
                    button hx-action=(Add::action().by(-1)) { "−" }
                    (counter(count))
                    button hx-action=(Add::action().by(1)) { "+" }
                }
            }
        }
    }
}

#[action("/add")]
struct Add {
    by: i64,
}

async fn add(Add { by }: Add) -> impl IntoResponse {
    let count = COUNT.fetch_add(by, Ordering::Relaxed) + by;

    partial! {
        counter(count),
        heading(count),
    }
}

#[fragment]
fn counter(count: i64) -> Markup {
    html! { output id=(Self) { (count) } }
}

#[fragment]
fn heading(count: i64) -> Markup {
    let title = match count {
        0 => "Zero",
        n if n % 2 == 0 => "Even",
        _ => "Odd",
    };
    html! { h1 id=(Self) { (title) } }
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let router = Router::new().view(home).action(add);
    let listener =
        tokio::net::TcpListener::bind("127.0.0.1:4002").await?;
    println!("listening on http://127.0.0.1:4002/");
    axum::serve(listener, router).await
}

Run

cargo run

Bundle assets#

Optional, but strongly recommended. The CDN version already works. Keeping assets beside your Rust pages and bundling them into one binary is central to ilek's design, but you can manage them yourself.

Now replace the CDN with a local entry point. With Bun installed, run in your project directory:

bun init --minimal --yes
bun add --exact htmx.org@4.0.2

Add the build dependency:

# Cargo.toml
[build-dependencies]
ilek = "0.5"

With ilek::Config::default(), the bundler picks up page.ts and index.ts under src/pages/<page>/. This single-file app uses src/index.ts instead:

// build.rs
fn main() {
    ilek::build(ilek::Config {
        entry_glob: "src/index.ts".into(),
        ..Default::default()
    });
}
// src/index.ts
import 'htmx.org';
import './index.css';
/* src/index.css */
body {
  margin: 2rem;
  font-family: system-ui, sans-serif;
}

main {
  display: flex;
  align-items: center;
  gap: 1rem;
}

output {
  font-size: 2rem;
}

In the page head, replace the CDN script with:

(ilek::assets!())

assets!() emits the script and stylesheet tags for the entry point beside main.rs.

Replace the router declaration in main():

let router = Router::new()
    .view(home)
    .action(add)
    .merge(ilek::assets_router!());

assets_router!() serves the bundled files embedded in the binary.

Restart the app and reload. The counter now loads local JS and CSS. Bun is needed to build, not to run the binary.

Full counter code
# Cargo.toml
[package]
name = "counter"
version = "0.1.0"
edition = "2024"

[dependencies]
ilek = "0.5"
axum = "0.8"
axum-extra = { version = "0.12", features = ["typed-routing"] }
maud = { version = "0.27", features = ["axum"] }
tokio = { version = "1", features = [
    "macros", "rt-multi-thread", "net",
] }

[build-dependencies]
ilek = "0.5"
// src/main.rs
use std::sync::atomic::{AtomicI64, Ordering};

use axum::{Router, response::IntoResponse};
use ilek::{
    RouterExt, action, fragment,
    maud::{DOCTYPE, Markup, html},
    partial, route,
};

static COUNT: AtomicI64 = AtomicI64::new(0);

#[route("/")]
struct HomePath;

async fn home(_: HomePath) -> Markup {
    let count = COUNT.load(Ordering::Relaxed);

    html! {
        (DOCTYPE)
        html lang="en" {
            head {
                meta charset="utf-8";
                meta name="viewport"
                    content="width=device-width, initial-scale=1";
                title { "Counter" }
                (ilek::assets!())
            }
            body {
                (heading(count))
                main {
                    button hx-action=(Add::action().by(-1)) { "−" }
                    (counter(count))
                    button hx-action=(Add::action().by(1)) { "+" }
                }
            }
        }
    }
}

#[action("/add")]
struct Add {
    by: i64,
}

async fn add(Add { by }: Add) -> impl IntoResponse {
    let count = COUNT.fetch_add(by, Ordering::Relaxed) + by;

    partial! {
        counter(count),
        heading(count),
    }
}

#[fragment]
fn counter(count: i64) -> Markup {
    html! { output id=(Self) { (count) } }
}

#[fragment]
fn heading(count: i64) -> Markup {
    let title = match count {
        0 => "Zero",
        n if n % 2 == 0 => "Even",
        _ => "Odd",
    };
    html! { h1 id=(Self) { (title) } }
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let router = Router::new()
        .view(home)
        .action(add)
        .merge(ilek::assets_router!());
    let listener =
        tokio::net::TcpListener::bind("127.0.0.1:4002").await?;
    println!("listening on http://127.0.0.1:4002/");
    axum::serve(listener, router).await
}
// build.rs
fn main() {
    ilek::build(ilek::Config {
        entry_glob: "src/index.ts".into(),
        ..Default::default()
    });
}
// package.json
{
  "private": true,
  "dependencies": {
    "htmx.org": "4.0.2"
  }
}
// src/index.ts
import 'htmx.org';
import './index.css';
/* src/index.css */
body {
  margin: 2rem;
  font-family: system-ui, sans-serif;
}

main {
  display: flex;
  align-items: center;
  gap: 1rem;
}

output {
  font-size: 2rem;
}

Run

bun install
cargo run

Next steps#