pagetop-website/doc/v0.6/es/src/how-to/htmx-polling.md
Manuel Cillero 345bd26974 📝 Document route access and custom authentication
Adapt the guides to the current PageTop API: Routes with the access of
each route, Layers, StaticFiles and the administration panel in the
core, with pagetop-admin reduced to the settings forms.

Add the "Connect your own authentication" guide, the mail test page and
the admin_path setting, and explain route access in the architecture
page.

Mount the books with their access through pagetop-mdbook.
2026-11-07 17:24:26 +01:00

5.1 KiB

Actualizar periódicamente

Objetivo: que una parte de la página se refresque sola cada pocos segundos (el progreso de una tarea larga, un contador, el estado de un servicio) y que deje de hacerlo cuando ya no haga falta.

Partimos de una aplicación con HTMX añadido.

1. Sondear cada pocos segundos

Con hx-trigger="every 2s", el elemento repite su petición cada dos segundos mientras siga en la página:

# use pagetop::prelude::*;
# fn f() -> Html {
Html::with(|_| html! {
    div hx-get="/sensors" hx-trigger="every 2s" {
        p { "Reading the sensors..." }
    }
})
# }

La ruta devuelve el contenido actualizado y HTMX lo pone dentro del div. Es la forma más sencilla de mantener un dato al día, sin conexiones permanentes ni JavaScript.

2. Parar cuando termina

Para el progreso de una tarea, el sondeo debe acabar cuando la tarea acaba. El truco es que cada respuesta decide si sigue el sondeo: el fragmento sustituye al elemento entero (outerHTML) y sólo lleva hx-trigger mientras la tarea no ha terminado.

# use pagetop::prelude::*;
fn progress(percent: u64) -> Markup {
    if percent < 100 {
        html! {
            div id="watering" hx-get="/watering" hx-trigger="every 1s" hx-swap="outerHTML" {
                progress value=(percent) max="100" {}
                " " (percent) "%"
            }
        }
    } else {
        html! {
            div id="watering" {
                p { "Watering finished." }
                button hx-post="/watering" hx-target="#watering" hx-swap="outerHTML" {
                    "Water again"
                }
            }
        }
    }
}

Cuando llega la versión final, sin hx-trigger, ya no queda nada que sondee.

Si prefieres no sustituir el elemento, hay otra forma de parar: responder con el código de estado 286. HTMX lo interpreta como «deja de sondear».

3. Arrancar la tarea

Un botón inicia la tarea con un POST; la respuesta es el primer fragmento de progreso, que ya sondea por su cuenta:

# use pagetop::prelude::*;
# use std::sync::Mutex;
# use std::time::Instant;
# static STARTED: Mutex<Option<Instant>> = Mutex::new(None);
# fn progress(_: u64) -> Markup { html! {} }
# fn started() -> std::sync::MutexGuard<'static, Option<Instant>> { STARTED.lock().unwrap() }
async fn start() -> Markup {
    *started() = Some(Instant::now());
    progress(0)
}

En una aplicación real, start lanzaría el trabajo en segundo plano y guardaría su estado; la ruta del sondeo sólo lo consulta. Aquí, para no depender de nada, el progreso se calcula a partir del tiempo transcurrido.

El ejemplo completo

use pagetop::prelude::*;

use std::sync::{Mutex, MutexGuard};
use std::time::Instant;

// Seconds that the simulated watering lasts.
const DURATION: u64 = 5;

static STARTED: Mutex<Option<Instant>> = Mutex::new(None);

fn started() -> MutexGuard<'static, Option<Instant>> {
    STARTED.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}

struct Watering;

#[async_trait]
impl Extension for Watering {
    fn dependencies(&self) -> Vec<ExtensionRef> {
        vec![&pagetop_htmx::Htmx]
    }

    fn configure_router(&self, routes: Routes) -> Routes {
        routes
            .public_route("/", web::get(home))
            .public_route("/watering", web::get(status).post(start))
    }
}

fn progress(percent: u64) -> Markup {
    if percent < 100 {
        html! {
            div id="watering" hx-get="/watering" hx-trigger="every 1s" hx-swap="outerHTML" {
                progress value=(percent) max="100" {}
                " " (percent) "%"
            }
        }
    } else {
        html! {
            div id="watering" {
                p { "Watering finished." }
                button hx-post="/watering" hx-target="#watering" hx-swap="outerHTML" {
                    "Water again"
                }
            }
        }
    }
}

async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
    Page::new(request)
        .with_title(Lc::n("Watering"))
        .with_child(Html::with(|_| html! {
            h1 { "Watering" }
            div id="watering" {
                button hx-post="/watering" hx-target="#watering" hx-swap="outerHTML" {
                    "Start watering"
                }
            }
        }))
        .render()
        .await
}

async fn start() -> Markup {
    *started() = Some(Instant::now());
    progress(0)
}

async fn status() -> Markup {
    let elapsed = started().map_or(DURATION, |since| since.elapsed().as_secs());
    progress((elapsed * 100 / DURATION).min(100))
}

#[pagetop::main]
async fn main() -> std::io::Result<()> {
    Application::prepare(&Watering).await.run().await
}

Comprueba

  1. Pulsa Start watering: aparece una barra que avanza cada segundo.
  2. A los cinco segundos, la barra da paso a «Watering finished.». En la pestaña Red, las peticiones a /watering se detienen.
  3. Water again vuelve a empezar.

Siguiente