Rebuild the website on the current PageTop API, with Bootsier as its
theme and edition 2024. Add the first Spanish guide (doc/v0.6/es) as an
mdBook book, built in build.rs and served with pagetop-mdbook, and the
/doc/latest/{lang} redirect.
Add `tools/doccheck.sh` to check the links of the guides and to compile,
run and test their examples against PageTop.
Move the configuration to config/common.toml and translate the README
to English.
4.6 KiB
Cargar contenido bajo demanda
Objetivo: que una parte de la página se cargue después que el resto: cuando el usuario la pida, en cuanto la página esté lista o cuando se haga visible. La página aparece antes, y lo costoso llega por su cuenta.
Partimos de una aplicación con HTMX añadido.
1. Al pulsar
El caso básico: un botón trae el contenido y lo pone en su sitio.
# use pagetop::prelude::*;
# fn f() -> Html {
Html::with(|_| html! {
button hx-get="/forecast" hx-target="#forecast" { "Show the forecast" }
div id="forecast" {}
})
# }
Para que el botón desaparezca y su lugar lo ocupe el contenido, apunta al propio botón y sustitúyelo entero:
# use pagetop::prelude::*;
# fn f() -> Html {
Html::with(|_| html! {
button hx-get="/forecast" hx-swap="outerHTML" { "Show the forecast" }
})
# }
2. En cuanto se carga la página
Con hx-trigger="load", el elemento pide su contenido nada más aparecer. Mientras llega, muestra
lo que tenga dentro:
# use pagetop::prelude::*;
# fn f() -> Html {
Html::with(|_| html! {
div hx-get="/forecast" hx-trigger="load" hx-swap="outerHTML" {
p { "Loading the forecast..." }
}
})
# }
Úsalo para lo que tarda (un servicio externo, una consulta pesada): la página se sirve al momento y ese bloque se completa después.
3. Cuando se hace visible
Con hx-trigger="revealed", la petición espera a que el elemento entre en la pantalla. Ideal para
lo que queda al final de una página larga, como los comentarios:
# use pagetop::prelude::*;
# fn f() -> Html {
Html::with(|_| html! {
section hx-get="/comments" hx-trigger="revealed" hx-swap="outerHTML" {
p { "Comments will load when you get here." }
}
})
# }
Si el usuario nunca baja hasta ahí, la petición no se hace.
4. Muestra que está cargando
Mientras dura una petición, HTMX añade la clase htmx-request al elemento que la hizo. Los
elementos con la clase htmx-indicator están ocultos y se muestran sólo durante la petición del
elemento que los contiene, o de quien los señale con hx-indicator:
# use pagetop::prelude::*;
# fn f() -> Html {
Html::with(|_| html! {
button hx-get="/forecast" hx-target="#forecast" hx-indicator="#spinner" {
"Show the forecast"
}
span id="spinner" class="htmx-indicator" { " Loading..." }
div id="forecast" {}
})
# }
HTMX trae los estilos de htmx-indicator, así que funciona sin escribir CSS.
El ejemplo completo
Una página con las tres formas, sobre las mismas dos rutas:
use pagetop::prelude::*;
struct Garden;
#[async_trait]
impl Extension for Garden {
fn dependencies(&self) -> Vec<ExtensionRef> {
vec![&pagetop_htmx::Htmx]
}
fn configure_router(&self, router: Router) -> Router {
router
.route("/", web::get(home))
.route("/forecast", web::get(forecast))
.route("/comments", web::get(comments))
}
}
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
Page::new(request)
.with_title(Lc::n("The garden today"))
.with_child(Html::with(|_| html! {
h1 { "The garden today" }
h2 { "Forecast" }
button hx-get="/forecast" hx-swap="outerHTML" { "Show the forecast" }
h2 { "Forecast, on load" }
div hx-get="/forecast" hx-trigger="load" hx-swap="outerHTML" {
p { "Loading the forecast..." }
}
h2 { "Comments" }
div style="height: 150vh" { p { "Scroll down..." } }
section hx-get="/comments" hx-trigger="revealed" hx-swap="outerHTML" {
p { "Comments will load when you get here." }
}
}))
.render()
.await
}
async fn forecast() -> Markup {
html! { p class="forecast" { "Sunny, 24 °C. Water in the evening." } }
}
async fn comments() -> Markup {
html! {
ul class="comments" {
li { "Ana: the lettuces are ready." }
li { "Luke: who has the hose key?" }
}
}
}
#[pagetop::main]
async fn main() -> std::io::Result<()> {
Application::prepare(&Garden).await.run().await
}
Comprueba
- Al abrir la página, el segundo bloque ya muestra la previsión: se pidió nada más cargarse.
- El botón del primero se sustituye por la previsión al pulsarlo.
- En la pestaña Red,
/commentsno aparece hasta que bajas al final de la página.
Siguiente
- Cargar más al hacer scroll:
revealedaplicado a listas largas. - Actualizar periódicamente: pedir el mismo fragmento cada pocos segundos.