# 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](htmx-setup.md). ## 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. ```rust,no_run # 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: ```rust,no_run # 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 `
  • `: ```rust,no_run # use pagetop::prelude::*; # fn entries(_: usize) -> Markup { html! {} } use serde::Deserialize; async fn diary(request: HttpRequest) -> Result { 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) -> Markup { entries(batch.page.max(1)) } ``` ## El ejemplo completo ```rust,no_run 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 { 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 { 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) -> 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 - [Ordenar y paginar sin recargar](htmx-tables.md): cuando el usuario necesita saltar a una página concreta, un paginador es mejor opción. - [Actualizar periódicamente](htmx-polling.md).