pagetop-website/doc/v0.6/es/src/how-to/htmx-infinite.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

4.4 KiB

Cargar más al hacer scroll

Objetivo: una lista larga que carga los siguientes elementos al pulsar «Load more» o, mejor aún, sola, cuando el usuario llega al final.

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

1. Un lote de elementos y un testigo

La ruta devuelve un lote de elementos y, si quedan más, un último elemento especial: el testigo, que sabe pedir el lote siguiente y ocupa su lugar.

# use pagetop::prelude::*;
const PER_PAGE: usize = 10;
const TOTAL: usize = 35;

fn entries(page: usize) -> Markup {
    let start = (page - 1) * PER_PAGE;
    let end = (start + PER_PAGE).min(TOTAL);
    let next = util::join!("/diary/entries?page=", (page + 1).to_string());
    html! {
        @for day in start + 1..=end {
            li { "Day " (day) ": the garden is growing." }
        }
        @if end < TOTAL {
            li {
                button hx-get=(next) hx-target="closest li" hx-swap="outerHTML" { "Load more" }
            }
        }
    }
}

Al pulsar el botón, la respuesta (diez elementos y un testigo nuevo) sustituye al testigo: la lista crece por abajo y el botón baja con ella. Cuando no quedan elementos, el último lote no trae testigo y la carga termina sola.

2. Sin botón: al llegar al final

Para cargar sin que el usuario pulse nada, el testigo se dispara con revealed, que ocurre cuando el elemento entra en la pantalla:

# use pagetop::prelude::*;
# fn f(next: String) -> Markup {
html! {
    li hx-get=(next) hx-trigger="revealed" hx-swap="outerHTML" { "Loading more..." }
}
# }

Es el mismo patrón con otro disparador. Si la lista está dentro de un contenedor con su propio scroll (overflow: auto), usa hx-trigger="intersect once", que funciona con cualquier contenedor.

3. La página y la ruta del lote

La página pinta el primer lote dentro de la lista; la ruta del lote devuelve sólo los <li>:

# use pagetop::prelude::*;
# fn entries(_: usize) -> Markup { html! {} }
use serde::Deserialize;

async fn diary(request: HttpRequest) -> Result<Markup, ErrorPage> {
    Page::new(request)
        .with_title(Lc::n("Garden diary"))
        .with_child(Html::with(|_| html! { ul id="diary" { (entries(1)) } }))
        .render()
        .await
}

#[derive(Deserialize)]
struct Batch {
    page: usize,
}

async fn more_entries(web::Query(batch): web::Query<Batch>) -> Markup {
    entries(batch.page.max(1))
}

El ejemplo completo

use pagetop::prelude::*;
use serde::Deserialize;

const PER_PAGE: usize = 10;
const TOTAL: usize = 35;

struct Diary;

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

    fn configure_router(&self, routes: Routes) -> Routes {
        routes
            .public_route("/", web::get(diary))
            .public_route("/diary/entries", web::get(more_entries))
    }
}

fn entries(page: usize) -> Markup {
    let start = (page - 1) * PER_PAGE;
    let end = (start + PER_PAGE).min(TOTAL);
    let next = util::join!("/diary/entries?page=", (page + 1).to_string());
    html! {
        @for day in start + 1..=end {
            li { "Day " (day) ": the garden is growing." }
        }
        @if end < TOTAL {
            li hx-get=(next) hx-trigger="revealed" hx-swap="outerHTML" { "Loading more..." }
        }
    }
}

async fn diary(request: HttpRequest) -> Result<Markup, ErrorPage> {
    Page::new(request)
        .with_title(Lc::n("Garden diary"))
        .with_child(Html::with(|_| html! { ul id="diary" { (entries(1)) } }))
        .render()
        .await
}

#[derive(Deserialize)]
struct Batch {
    page: usize,
}

async fn more_entries(web::Query(batch): web::Query<Batch>) -> Markup {
    entries(batch.page.max(1))
}

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

Comprueba

  1. Abre la página y baja: cada vez que el testigo «Loading more...» asoma por abajo, llegan diez días más. Si la ventana es alta y el testigo ya se ve al cargar, el segundo lote llega sin esperar: está a la vista.
  2. Sigue bajando hasta el día 35: el testigo ya no aparece.
  3. En la pestaña Red hay tres peticiones a /diary/entries, una por lote.

Siguiente