# Tareas del huerto con HTMX En este tutorial construyes la lista de tareas de un huerto vecinal: añadir tareas, marcarlas como hechas, editarlas y borrarlas, **todo sin recargar la página** y sin escribir una línea de JavaScript. El servidor sigue generando todo el HTML; [HTMX](https://htmx.org) sólo se encarga de pedir fragmentos y colocarlos en su sitio. - **Tiempo:** unos 30 minutos. - **Necesitas:** haber hecho [Tu primera aplicación](first-app.md). Conocer HTMX no hace falta. - **Al terminar tendrás:** una aplicación de un solo archivo, con siete rutas y sus pruebas. > **La idea en una frase.** Un atributo `hx-*` en un elemento dice «cuando pase esto, pide aquella > URL y pon la respuesta allí». El servidor responde con HTML, no con JSON. ## 1. Crea el proyecto ```sh cargo new garden-tasks cd garden-tasks ``` Añade las dependencias a `Cargo.toml`: ```toml [dependencies] pagetop = { git = "https://git.cillero.es/manuelcillero/pagetop" } pagetop-htmx = { git = "https://git.cillero.es/manuelcillero/pagetop" } serde = { version = "1", features = ["derive"] } ``` `pagetop-htmx` es la extensión que añade HTMX 2 a todas las páginas y trae ayudas para responder a sus peticiones. `serde` sirve para leer los formularios. ## 2. Un almacén y una página Las tareas se guardan en memoria, en un vector protegido por un `Mutex`: así el tutorial se centra en HTMX. En el [siguiente tutorial](database.md) las pasarás a una base de datos. Sustituye `src/main.rs` por esto: ```rust,no_run use pagetop::prelude::*; use std::sync::{LazyLock, Mutex, MutexGuard}; // **< The task store >***************************************************************************** #[derive(Clone)] struct Task { id: u32, title: String, done: bool, } #[derive(Default)] struct Store { last_id: u32, tasks: Vec, } impl Store { fn add(&mut self, title: String) -> Task { self.last_id += 1; let task = Task { id: self.last_id, title, done: false }; self.tasks.push(task.clone()); task } fn get(&mut self, id: u32) -> Option<&mut Task> { self.tasks.iter_mut().find(|task| task.id == id) } fn remove(&mut self, id: u32) { self.tasks.retain(|task| task.id != id); } fn pending(&self) -> usize { self.tasks.iter().filter(|task| !task.done).count() } } static STORE: LazyLock> = LazyLock::new(Mutex::default); fn store() -> MutexGuard<'static, Store> { // The lock is only poisoned by a panic while it is held; the tasks are still valid. STORE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } // **< The application >**************************************************************************** struct GardenTasks; #[async_trait] impl Extension for GardenTasks { async fn initialize(&self) -> Result<(), BoxError> { store().add("Water the tomatoes".into()); store().add("Turn the compost".into()); Ok(()) } fn configure_router(&self, routes: Routes) -> Routes { routes.public_route("/", web::get(home)) } } async fn home(request: HttpRequest) -> Result { let (tasks, pending) = { let store = store(); (store.tasks.clone(), store.pending()) }; Page::new(request) .with_title(Lc::n("Garden tasks")) .with_child(Html::with(move |_| html! { h1 { "Garden tasks" } p { "Pending: " strong id="pending" { (pending) } } ul id="tasks" { @for task in &tasks { (task_item(task)) } } })) .render() .await } fn task_item(task: &Task) -> Markup { html! { li { (task.title) } } } #[pagetop::main] async fn main() -> std::io::Result<()> { Application::prepare(&GardenTasks).await.run().await } ``` Arranca con `cargo run` y abre : verás el título, el contador de pendientes y las dos tareas que `initialize()` añade al arrancar. Fíjate en dos detalles que vas a aprovechar enseguida: - La lista tiene `id="tasks"` y el contador `id="pending"`: serán los **destinos** donde HTMX coloque los fragmentos. - `task_item()` pinta una sola tarea. La página la usa para la lista completa y, a partir del paso siguiente, las rutas de HTMX la usarán para devolver una tarea suelta. **El mismo código genera la página y los fragmentos.** ## 3. Añadir tareas sin recargar Primero, declara la extensión HTMX como dependencia. Con eso, todas las páginas cargan el *script* de HTMX: ```rust,no_run # use pagetop::prelude::*; # struct GardenTasks; # async fn home() {} # async fn create() {} #[async_trait] impl Extension for GardenTasks { fn dependencies(&self) -> Vec { vec![&pagetop_htmx::Htmx] } // ... initialize() as before ... fn configure_router(&self, routes: Routes) -> Routes { routes .public_route("/", web::get(home)) .public_route("/tasks", web::post(create)) } } ``` Después, el formulario. Es un `Form` normal, que funciona también sin JavaScript (`action` y `method`), al que se añaden cuatro atributos `hx-*` con `with_prop()`: ```rust,no_run # use pagetop::prelude::*; use pagetop_htmx::prelude::*; fn add_form() -> Form { Form::new() .with_action("/tasks") .with_method(form::Method::Post) .with_prop(PropsOp::set(hx::POST, "/tasks")) .with_prop(PropsOp::set(hx::TARGET, "#tasks")) .with_prop(PropsOp::set(hx::SWAP, hx::swap::BEFORE_END)) .with_prop(PropsOp::set(hx::on_htmx("after-request"), "this.reset()")) .with_child( form::input::Field::text() .with_name("title") .with_label(Lc::n("New task")) .with_required(true), ) .with_child(Button::submit(Lc::n("Add"))) } ``` Leído en voz alta: «al enviar el formulario, haz un `POST` a `/tasks`, coloca la respuesta **al final** (`beforeend`) de `#tasks` y, cuando termine, vacía el formulario». Añádelo a la página, entre el contador y la lista: ```rust,no_run # use pagetop::prelude::*; # fn add_form() -> Form { Form::new() } # fn task_item(_: &u32) -> Markup { html! {} } # async fn home(request: HttpRequest) -> Result { # let (tasks, pending) = (vec![1u32], 1); Page::new(request) .with_title(Lc::n("Garden tasks")) .with_child(Html::with(move |_| html! { h1 { "Garden tasks" } p { "Pending: " strong id="pending" { (pending) } } })) .with_child(add_form()) .with_child(Html::with(move |_| html! { ul id="tasks" { @for task in &tasks { (task_item(task)) } } })) .render() .await # } ``` Y la ruta que recibe el formulario. Devuelve **sólo el `
  • ` de la tarea nueva**: ```rust,no_run # use pagetop::prelude::*; # use pagetop_htmx::prelude::*; # struct Task { title: String } # struct Store; # impl Store { fn add(&mut self, title: String) -> Task { Task { title } } } # fn store() -> Store { Store } # fn task_item(_: &Task) -> Markup { html! {} } use serde::Deserialize; #[derive(Deserialize)] struct TaskForm { title: String, } async fn create(request: HttpRequest, web::Form(form): web::Form) -> Response { let title = form.title.trim(); let added = (!title.is_empty()).then(|| store().add(title.to_string())); if !request.is_htmx() { // Without JavaScript the browser posts the form: back to the list. return Redirect::see_other("/"); } match added { Some(task) => HtmxResponse::new(task_item(&task)).into_response(), None => HtmxResponse::empty().into_response(), } } ``` **Pruébalo.** Reinicia, escribe «Plant lettuces» y pulsa *Add*. La tarea aparece al final de la lista y el campo se vacía, sin recargar. Abre las herramientas de desarrollo del navegador (pestaña *Red*): la respuesta a `POST /tasks` es una sola línea, `
  • Plant lettuces
  • `. Qué ha pasado: 1. HTMX interceptó el envío del formulario y lo mandó por su cuenta, con la cabecera `HX-Request: true`. 2. `request.is_htmx()` lee esa cabecera, así que la ruta devolvió el fragmento. 3. HTMX lo insertó al final de `#tasks`, como pedía `hx-swap`. Si desactivas JavaScript, el mismo formulario se envía de la forma clásica y la ruta responde con una redirección a `/`: la aplicación sigue funcionando. Esto se llama **mejora progresiva**. > **¿Y el contador?** Se ha quedado igual. Lo arreglas en el paso 5. ## 4. Marcar tareas como hechas Cada tarea lleva ahora una casilla. Al cambiarla, HTMX hace un `PATCH` y sustituye **la tarea entera** por la respuesta: ```rust,no_run # use pagetop::prelude::*; # struct Task { id: u32, title: String, done: bool } fn task_url(task: &Task) -> String { util::join!("/tasks/", task.id.to_string()) } fn task_item(task: &Task) -> Markup { let url = task_url(task); html! { li hx-target="this" hx-swap="outerHTML" { input type="checkbox" checked[task.done] hx-patch=(util::join!(url, "/toggle")); " " @if task.done { s { (task.title) } } @else { (task.title) } } } } ``` El truco está en el `
  • `: `hx-target="this"` y `hx-swap="outerHTML"` se **heredan**, así que cualquier elemento de dentro que haga una petición sustituye el `
  • ` completo. Lo aprovecharás también para editar y borrar. En `input type="checkbox"`, HTMX dispara la petición con el evento `change`, sin que tengas que indicarlo. La ruta: ```rust,no_run # use pagetop::prelude::*; # use pagetop_htmx::prelude::*; # struct Task { done: bool } # struct Store; # impl Store { fn get(&mut self, _: u32) -> Option<&mut Task> { None } } # fn store() -> Store { Store } # fn task_item(_: &Task) -> Markup { html! {} } fn not_found() -> Response { web::http::StatusCode::NOT_FOUND.into_response() } async fn toggle(web::Path(id): web::Path) -> Response { let mut store = store(); let Some(task) = store.get(id) else { return not_found(); }; task.done = !task.done; HtmxResponse::new(task_item(task)).into_response() } ``` Regístrala con `.public_route("/tasks/{id}/toggle", web::patch(toggle))`. Marca una tarea: queda tachada. ## 5. El contador, fuera de banda Cada cambio debe actualizar también el contador de pendientes, que está **fuera** del `
  • `. Para eso, la respuesta lleva un segundo fragmento marcado con `hx-swap-oob="true"`: HTMX lo busca por su `id` en toda la página y lo sustituye aparte, sin importar el destino de la petición. ```rust,no_run # use pagetop::prelude::*; fn pending_update(pending: usize) -> Markup { html! { strong id="pending" hx-swap-oob="true" { (pending) } } } ``` `HtmxResponse::oob()` lo añade a la respuesta. En `toggle`: ```rust,no_run # use pagetop::prelude::*; # use pagetop_htmx::prelude::*; # struct Task { done: bool } # struct Store; # impl Store { # fn get(&mut self, _: u32) -> Option<&mut Task> { None } # fn pending(&self) -> usize { 0 } # } # fn store() -> Store { Store } # fn task_item(_: &Task) -> Markup { html! {} } # fn pending_update(_: usize) -> Markup { html! {} } # fn not_found() -> Response { todo!() } # async fn toggle(web::Path(id): web::Path) -> Response { # let mut store = store(); # let Some(task) = store.get(id) else { # return not_found(); # }; # task.done = !task.done; let item = task_item(task); HtmxResponse::new(item) .oob(pending_update(store.pending())) .into_response() # } ``` Y en `create`, al añadir una tarea: ```rust,ignore Some(task) => HtmxResponse::new(task_item(&task)) .oob(pending_update(store().pending())) .into_response(), ``` Ahora el contador sigue el ritmo de la lista. Una petición, dos zonas actualizadas. ## 6. Borrar con confirmación Añade un botón a cada tarea, después del título: ```rust,ignore button type="button" hx-delete=(url) hx-confirm="Delete this task?" { "Delete" } ``` `hx-confirm` pide confirmación al usuario antes de enviar nada. La ruta borra la tarea y responde con un fragmento principal **vacío**: como el destino es el `
  • ` con `outerHTML`, HTMX lo sustituye por nada, es decir, lo elimina. El contador viaja fuera de banda, como antes: ```rust,no_run # use pagetop::prelude::*; # use pagetop_htmx::prelude::*; # struct Store; # impl Store { # fn remove(&mut self, _: u32) {} # fn pending(&self) -> usize { 0 } # } # fn store() -> Store { Store } # fn pending_update(_: usize) -> Markup { html! {} } async fn remove(web::Path(id): web::Path) -> Response { let mut store = store(); store.remove(id); HtmxResponse::empty() .oob(pending_update(store.pending())) .into_response() } ``` Regístrala en la ruta de cada tarea: `.public_route("/tasks/{id}", web::delete(remove))`. ## 7. Editar en línea El último botón de cada tarea pide su versión editable: ```rust,ignore button type="button" hx-get=(util::join!(url, "/edit")) { "Edit" } ``` La ruta `/tasks/{id}/edit` devuelve el mismo `
  • `, pero con un pequeño formulario dentro: ```rust,no_run # use pagetop::prelude::*; # struct Task { id: u32, title: String } # fn task_url(_: &Task) -> String { String::new() } fn edit_item(task: &Task) -> Markup { let url = task_url(task); html! { li hx-target="this" hx-swap="outerHTML" { form hx-put=(url) { input type="text" name="title" value=(task.title) required autofocus; button type="submit" { "Save" } button type="button" hx-get=(url) { "Cancel" } } } } } ``` *Save* envía el formulario con `PUT /tasks/{id}` y *Cancel* pide la tarea sin cambios con `GET /tasks/{id}`. Las tres rutas devuelven un `
  • `: ```rust,no_run # use pagetop::prelude::*; # use pagetop_htmx::prelude::*; # use serde::Deserialize; # struct Task { title: String } # struct Store; # impl Store { fn get(&mut self, _: u32) -> Option<&mut Task> { None } } # fn store() -> Store { Store } # fn task_item(_: &Task) -> Markup { html! {} } # fn edit_item(_: &Task) -> Markup { html! {} } # fn not_found() -> Response { todo!() } # #[derive(Deserialize)] # struct TaskForm { title: String } async fn edit(web::Path(id): web::Path) -> Response { match store().get(id) { Some(task) => HtmxResponse::new(edit_item(task)).into_response(), None => not_found(), } } async fn show(web::Path(id): web::Path) -> Response { match store().get(id) { Some(task) => HtmxResponse::new(task_item(task)).into_response(), None => not_found(), } } async fn update(web::Path(id): web::Path, web::Form(form): web::Form) -> Response { let mut store = store(); let Some(task) = store.get(id) else { return not_found(); }; let title = form.title.trim(); if !title.is_empty() { task.title = title.to_string(); } HtmxResponse::new(task_item(task)).into_response() } ``` Las rutas quedan así: ```rust,no_run # use pagetop::prelude::*; # async fn home() {} # async fn create() {} # async fn show() {} # async fn update() {} # async fn remove() {} # async fn edit() {} # async fn toggle() {} # struct GardenTasks; # #[async_trait] # impl Extension for GardenTasks { fn configure_router(&self, routes: Routes) -> Routes { routes .public_route("/", web::get(home)) .public_route("/tasks", web::post(create)) .public_route("/tasks/{id}", web::get(show).put(update).delete(remove)) .public_route("/tasks/{id}/edit", web::get(edit)) .public_route("/tasks/{id}/toggle", web::patch(toggle)) } # } ``` ## 8. Prueba la aplicación Las rutas de HTMX son rutas normales, así que se prueban como cualquier otra. Basta con enviar la cabecera `HX-Request`, como hace HTMX. Añade al final de `src/main.rs` una prueba que recorre el ciclo completo de una tarea: ```rust # use pagetop::prelude::*; # use pagetop_htmx::prelude::*; # use serde::Deserialize; # use std::sync::{LazyLock, Mutex, MutexGuard}; # #[derive(Clone)] # struct Task { id: u32, title: String, done: bool } # #[derive(Default)] # struct Store { last_id: u32, tasks: Vec } # impl Store { # fn add(&mut self, title: String) -> Task { # self.last_id += 1; # let task = Task { id: self.last_id, title, done: false }; # self.tasks.push(task.clone()); # task # } # fn get(&mut self, id: u32) -> Option<&mut Task> { # self.tasks.iter_mut().find(|task| task.id == id) # } # fn remove(&mut self, id: u32) { # self.tasks.retain(|task| task.id != id); # } # fn pending(&self) -> usize { # self.tasks.iter().filter(|task| !task.done).count() # } # } # static STORE: LazyLock> = LazyLock::new(Mutex::default); # fn store() -> MutexGuard<'static, Store> { # STORE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) # } # struct GardenTasks; # #[async_trait] # impl Extension for GardenTasks { # fn dependencies(&self) -> Vec { # vec![&pagetop_htmx::Htmx] # } # async fn initialize(&self) -> Result<(), BoxError> { # store().add("Water the tomatoes".into()); # store().add("Turn the compost".into()); # Ok(()) # } # fn configure_router(&self, routes: Routes) -> Routes { # routes # .public_route("/", web::get(home)) # .public_route("/tasks", web::post(create)) # .public_route("/tasks/{id}", web::get(show).put(update).delete(remove)) # .public_route("/tasks/{id}/edit", web::get(edit)) # .public_route("/tasks/{id}/toggle", web::patch(toggle)) # } # } # async fn home(request: HttpRequest) -> Result { # let (tasks, pending) = { # let store = store(); # (store.tasks.clone(), store.pending()) # }; # Page::new(request) # .with_title(Lc::n("Garden tasks")) # .with_child(Html::with(move |_| html! { # h1 { "Garden tasks" } # p { "Pending: " strong id="pending" { (pending) } } # })) # .with_child(add_form()) # .with_child(Html::with(move |_| html! { # ul id="tasks" { # @for task in &tasks { # (task_item(task)) # } # } # })) # .render() # .await # } # fn add_form() -> Form { # Form::new() # .with_action("/tasks") # .with_method(form::Method::Post) # .with_prop(PropsOp::set(hx::POST, "/tasks")) # .with_prop(PropsOp::set(hx::TARGET, "#tasks")) # .with_prop(PropsOp::set(hx::SWAP, hx::swap::BEFORE_END)) # .with_prop(PropsOp::set(hx::on_htmx("after-request"), "this.reset()")) # .with_child( # form::input::Field::text() # .with_name("title") # .with_label(Lc::n("New task")) # .with_required(true), # ) # .with_child(Button::submit(Lc::n("Add"))) # } # fn task_url(task: &Task) -> String { # util::join!("/tasks/", task.id.to_string()) # } # fn task_item(task: &Task) -> Markup { # let url = task_url(task); # html! { # li hx-target="this" hx-swap="outerHTML" { # input type="checkbox" checked[task.done] hx-patch=(util::join!(url, "/toggle")); # " " # @if task.done { # s { (task.title) } # } @else { # (task.title) # } # " " # button type="button" hx-get=(util::join!(url, "/edit")) { "Edit" } # button type="button" hx-delete=(url) hx-confirm="Delete this task?" { "Delete" } # } # } # } # fn edit_item(task: &Task) -> Markup { # let url = task_url(task); # html! { # li hx-target="this" hx-swap="outerHTML" { # form hx-put=(url) { # input type="text" name="title" value=(task.title) required autofocus; # button type="submit" { "Save" } # button type="button" hx-get=(url) { "Cancel" } # } # } # } # } # fn pending_update(pending: usize) -> Markup { # html! { strong id="pending" hx-swap-oob="true" { (pending) } } # } # fn not_found() -> Response { # web::http::StatusCode::NOT_FOUND.into_response() # } # #[derive(Deserialize)] # struct TaskForm { title: String } # async fn create(request: HttpRequest, web::Form(form): web::Form) -> Response { # let title = form.title.trim(); # let added = (!title.is_empty()).then(|| store().add(title.to_string())); # if !request.is_htmx() { # return Redirect::see_other("/"); # } # match added { # Some(task) => HtmxResponse::new(task_item(&task)) # .oob(pending_update(store().pending())) # .into_response(), # None => HtmxResponse::empty().into_response(), # } # } # async fn toggle(web::Path(id): web::Path) -> Response { # let mut store = store(); # let Some(task) = store.get(id) else { # return not_found(); # }; # task.done = !task.done; # let item = task_item(task); # HtmxResponse::new(item).oob(pending_update(store.pending())).into_response() # } # async fn remove(web::Path(id): web::Path) -> Response { # let mut store = store(); # store.remove(id); # HtmxResponse::empty().oob(pending_update(store.pending())).into_response() # } # async fn edit(web::Path(id): web::Path) -> Response { # match store().get(id) { # Some(task) => HtmxResponse::new(edit_item(task)).into_response(), # None => not_found(), # } # } # async fn show(web::Path(id): web::Path) -> Response { # match store().get(id) { # Some(task) => HtmxResponse::new(task_item(task)).into_response(), # None => not_found(), # } # } # async fn update(web::Path(id): web::Path, web::Form(form): web::Form) -> Response { # let mut store = store(); # let Some(task) = store.get(id) else { # return not_found(); # }; # let title = form.title.trim(); # if !title.is_empty() { # task.title = title.to_string(); # } # HtmxResponse::new(task_item(task)).into_response() # } #[cfg(test)] mod tests { use super::*; // Sends a request as HTMX does: with the `HX-Request` header. fn htmx(request: web::test::TestRequest) -> web::Request { request.header("hx-request", "true").to_request() } #[pagetop::test] async fn tasks_are_added_toggled_and_removed() { let app = web::test::init_router(Application::prepare(&GardenTasks).await.test()); // Without HTMX, the form redirects to the list. let request = web::test::TestRequest::post() .uri("/tasks") .form("title=Buy+seeds") .to_request(); let response = web::test::send_request(&app, request).await; assert_eq!(response.status(), web::http::StatusCode::SEE_OTHER); // With HTMX, adding returns the new item, and the counter out of band. let request = htmx(web::test::TestRequest::post().uri("/tasks").form("title=Plant+lettuces")); let body = web::test::read_body_text(web::test::send_request(&app, request).await).await; assert!(body.starts_with("4"#)); // Toggling returns the item crossed out. let request = htmx(web::test::TestRequest::patch().uri("/tasks/4/toggle")); let body = web::test::read_body_text(web::test::send_request(&app, request).await).await; assert!(body.contains("Plant lettuces")); assert!(body.contains(">3")); // Removing returns only the counter. let request = htmx(web::test::TestRequest::delete().uri("/tasks/4")); let body = web::test::read_body_text(web::test::send_request(&app, request).await).await; assert_eq!(body, r#"3"#); } } ``` Y ejecútala: ```sh cargo test ``` ```text running 1 test test tests::tasks_are_added_toggled_and_removed ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out ``` La prueba comprueba justo lo que importa: qué HTML devuelve cada ruta. Lo que HTMX hace después con él lo dicen los atributos `hx-*`, y no hay más lógica que probar en el navegador. ## El código completo ```rust,no_run use pagetop::prelude::*; use pagetop_htmx::prelude::*; use serde::Deserialize; use std::sync::{LazyLock, Mutex, MutexGuard}; // **< The task store >***************************************************************************** #[derive(Clone)] struct Task { id: u32, title: String, done: bool, } #[derive(Default)] struct Store { last_id: u32, tasks: Vec, } impl Store { fn add(&mut self, title: String) -> Task { self.last_id += 1; let task = Task { id: self.last_id, title, done: false }; self.tasks.push(task.clone()); task } fn get(&mut self, id: u32) -> Option<&mut Task> { self.tasks.iter_mut().find(|task| task.id == id) } fn remove(&mut self, id: u32) { self.tasks.retain(|task| task.id != id); } fn pending(&self) -> usize { self.tasks.iter().filter(|task| !task.done).count() } } static STORE: LazyLock> = LazyLock::new(Mutex::default); fn store() -> MutexGuard<'static, Store> { // The lock is only poisoned by a panic while it is held; the tasks are still valid. STORE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } // **< The application >**************************************************************************** struct GardenTasks; #[async_trait] impl Extension for GardenTasks { fn dependencies(&self) -> Vec { vec![&pagetop_htmx::Htmx] } async fn initialize(&self) -> Result<(), BoxError> { store().add("Water the tomatoes".into()); store().add("Turn the compost".into()); Ok(()) } fn configure_router(&self, routes: Routes) -> Routes { routes .public_route("/", web::get(home)) .public_route("/tasks", web::post(create)) .public_route("/tasks/{id}", web::get(show).put(update).delete(remove)) .public_route("/tasks/{id}/edit", web::get(edit)) .public_route("/tasks/{id}/toggle", web::patch(toggle)) } } #[pagetop::main] async fn main() -> std::io::Result<()> { Application::prepare(&GardenTasks).await.run().await } // **< Markup >************************************************************************************* fn add_form() -> Form { Form::new() .with_action("/tasks") .with_method(form::Method::Post) .with_prop(PropsOp::set(hx::POST, "/tasks")) .with_prop(PropsOp::set(hx::TARGET, "#tasks")) .with_prop(PropsOp::set(hx::SWAP, hx::swap::BEFORE_END)) .with_prop(PropsOp::set(hx::on_htmx("after-request"), "this.reset()")) .with_child( form::input::Field::text() .with_name("title") .with_label(Lc::n("New task")) .with_required(true), ) .with_child(Button::submit(Lc::n("Add"))) } fn task_url(task: &Task) -> String { util::join!("/tasks/", task.id.to_string()) } fn task_item(task: &Task) -> Markup { let url = task_url(task); html! { li hx-target="this" hx-swap="outerHTML" { input type="checkbox" checked[task.done] hx-patch=(util::join!(url, "/toggle")); " " @if task.done { s { (task.title) } } @else { (task.title) } " " button type="button" hx-get=(util::join!(url, "/edit")) { "Edit" } button type="button" hx-delete=(url) hx-confirm="Delete this task?" { "Delete" } } } } fn edit_item(task: &Task) -> Markup { let url = task_url(task); html! { li hx-target="this" hx-swap="outerHTML" { form hx-put=(url) { input type="text" name="title" value=(task.title) required autofocus; button type="submit" { "Save" } button type="button" hx-get=(url) { "Cancel" } } } } } fn pending_update(pending: usize) -> Markup { html! { strong id="pending" hx-swap-oob="true" { (pending) } } } // **< Handlers >*********************************************************************************** async fn home(request: HttpRequest) -> Result { let (tasks, pending) = { let store = store(); (store.tasks.clone(), store.pending()) }; Page::new(request) .with_title(Lc::n("Garden tasks")) .with_child(Html::with(move |_| html! { h1 { "Garden tasks" } p { "Pending: " strong id="pending" { (pending) } } })) .with_child(add_form()) .with_child(Html::with(move |_| html! { ul id="tasks" { @for task in &tasks { (task_item(task)) } } })) .render() .await } #[derive(Deserialize)] struct TaskForm { title: String, } fn not_found() -> Response { web::http::StatusCode::NOT_FOUND.into_response() } async fn create(request: HttpRequest, web::Form(form): web::Form) -> Response { let title = form.title.trim(); let added = (!title.is_empty()).then(|| store().add(title.to_string())); if !request.is_htmx() { // Without JavaScript the browser posts the form: back to the list. return Redirect::see_other("/"); } match added { Some(task) => HtmxResponse::new(task_item(&task)) .oob(pending_update(store().pending())) .into_response(), None => HtmxResponse::empty().into_response(), } } async fn toggle(web::Path(id): web::Path) -> Response { let mut store = store(); let Some(task) = store.get(id) else { return not_found(); }; task.done = !task.done; let item = task_item(task); HtmxResponse::new(item) .oob(pending_update(store.pending())) .into_response() } async fn remove(web::Path(id): web::Path) -> Response { let mut store = store(); store.remove(id); HtmxResponse::empty() .oob(pending_update(store.pending())) .into_response() } async fn edit(web::Path(id): web::Path) -> Response { match store().get(id) { Some(task) => HtmxResponse::new(edit_item(task)).into_response(), None => not_found(), } } async fn show(web::Path(id): web::Path) -> Response { match store().get(id) { Some(task) => HtmxResponse::new(task_item(task)).into_response(), None => not_found(), } } async fn update(web::Path(id): web::Path, web::Form(form): web::Form) -> Response { let mut store = store(); let Some(task) = store.get(id) else { return not_found(); }; let title = form.title.trim(); if !title.is_empty() { task.title = title.to_string(); } HtmxResponse::new(task_item(task)).into_response() } ``` ## Lo que has construido - Una página que el servidor genera entera, y **siete rutas** que devuelven fragmentos de HTML. - Interacción sin recargas ni JavaScript propio: cada comportamiento es un atributo `hx-*`. - Un formulario que funciona también **sin JavaScript** (mejora progresiva). - Actualizaciones de dos zonas con una sola respuesta (*out-of-band*). - Pruebas que verifican el HTML de cada ruta, sin navegador. ## Siguiente - [Guarda las tareas en una base de datos](database.md): el mismo tutorial, con SQLite y SeaORM. - Las guías de [Interactividad con HTMX](../how-to/htmx-setup.md): búsqueda en vivo, *scroll* infinito, validación al vuelo, sondeo periódico y más. - [HTML por la red: por qué HTMX](../explanation/htmx.md), si quieres entender el enfoque.