✨ Serve the PageTop guides with pagetop-mdbook
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.
This commit is contained in:
parent
e41e71cc78
commit
1a41a456d4
80 changed files with 14112 additions and 1218 deletions
216
doc/v0.6/es/src/how-to/htmx-setup.md
Normal file
216
doc/v0.6/es/src/how-to/htmx-setup.md
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
# Añadir HTMX a una aplicación
|
||||
|
||||
**Objetivo:** que tus páginas carguen [HTMX](https://htmx.org), que sus elementos pidan fragmentos
|
||||
de HTML al servidor y que tus rutas sepan responderlos.
|
||||
|
||||
Si es tu primer contacto con HTMX, el tutorial [Tareas del huerto con
|
||||
HTMX](../tutorials/htmx-tasks.md) lo presenta paso a paso. Esta guía reúne lo esencial para
|
||||
cualquier aplicación.
|
||||
|
||||
## 1. Declara la extensión
|
||||
|
||||
Añade `pagetop-htmx` a `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
pagetop-htmx = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
||||
```
|
||||
|
||||
Y declárala como dependencia de tu extensión:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
pub struct MyApp;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for MyApp {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
No hace falta nada más: la extensión añade el *script* de HTMX 2 a **todas** las páginas, con
|
||||
`defer`, y lo sirve desde el propio binario. No hay que descargar nada ni configurar una CDN.
|
||||
|
||||
## 2. Escribe atributos `hx-*` en `html!`
|
||||
|
||||
Los atributos de HTMX se escriben en `html!` como cualquier otro:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Html {
|
||||
Html::with(|_| html! {
|
||||
button hx-get="/time" hx-target="#time" { "What time is it?" }
|
||||
span id="time" {}
|
||||
})
|
||||
# }
|
||||
```
|
||||
|
||||
Al pulsar el botón, HTMX hace `GET /time` y pone la respuesta dentro de `#time`. Los atributos
|
||||
principales:
|
||||
|
||||
| Atributo | Qué indica | Por defecto |
|
||||
|---|---|---|
|
||||
| `hx-get`, `hx-post`, `hx-put`, `hx-patch`, `hx-delete` | Método y URL de la petición | - |
|
||||
| `hx-trigger` | Qué evento la lanza | `click`; `change` en campos; `submit` en formularios |
|
||||
| `hx-target` | Dónde va la respuesta (selector CSS, `this`, `closest tr`...) | El propio elemento |
|
||||
| `hx-swap` | Cómo se coloca | `innerHTML`: sustituye el contenido |
|
||||
|
||||
La lista completa está en la [referencia de HTMX](../reference/htmx.md).
|
||||
|
||||
## 3. Ponlos en componentes con `with_prop()`
|
||||
|
||||
Los componentes no conocen HTMX, pero todos aceptan atributos con `with_prop()`. El módulo `hx` de
|
||||
`pagetop-htmx` tiene una constante para cada atributo y para sus valores habituales:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
# fn f() -> Button {
|
||||
Button::plain(Lc::n("What time is it?"))
|
||||
.with_prop(PropsOp::set(hx::GET, "/time"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "#time"))
|
||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::INNER_HTML))
|
||||
# }
|
||||
```
|
||||
|
||||
Con las constantes, una errata como `hx::GTE` no compila; escrita como texto, `"hx-gte"` fallaría
|
||||
en silencio en el navegador.
|
||||
|
||||
## 4. Responde con un fragmento
|
||||
|
||||
Una ruta para HTMX devuelve **sólo el trozo de HTML** que va en el destino, no una página. Lo más
|
||||
sencillo es devolver `Markup`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
async fn time() -> Markup {
|
||||
html! { (Utc::now().format("%H:%M:%S")) " UTC" }
|
||||
}
|
||||
```
|
||||
|
||||
Si además necesitas cabeceras de HTMX (cambiar el destino, disparar eventos, redirigir...),
|
||||
devuelve un `HtmxResponse`. Lo verás en [Dirigir al navegador desde el
|
||||
servidor](htmx-responses.md):
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
async fn time() -> HtmxResponse {
|
||||
HtmxResponse::new(html! { (Utc::now().format("%H:%M:%S")) " UTC" })
|
||||
.trigger("timeShown")
|
||||
}
|
||||
```
|
||||
|
||||
## 5. Renderiza componentes en un fragmento
|
||||
|
||||
Fuera de una `Page`, un componente se renderiza con un `Context` creado a partir de la petición. El
|
||||
contexto aporta el idioma, el tema y las rutas, así que el fragmento sale igual que dentro de la
|
||||
página:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
async fn notice(request: HttpRequest) -> HtmxResponse {
|
||||
let mut cx = Context::new(request);
|
||||
let mut badge = Badge::success(Lc::n("Saved"));
|
||||
HtmxResponse::new(badge.render(&mut cx).await)
|
||||
}
|
||||
```
|
||||
|
||||
> **Los recursos de un componente no viajan en un fragmento.** Si un componente añade su hoja de
|
||||
> estilos o su *script* al contexto, en una página acaban en el `<head>`; en un fragmento suelto no
|
||||
> hay `<head>` donde ponerlos. Asegúrate de que la página que recibe el fragmento ya los carga, por
|
||||
> ejemplo usando ese mismo componente en ella o añadiéndolos con `with_assets()`.
|
||||
|
||||
## 6. Una ruta, dos respuestas
|
||||
|
||||
Cuando la misma URL puede pedirse con HTMX (para un fragmento) o directamente (al recargar, desde
|
||||
un enlace compartido o sin JavaScript), comprueba quién llama con `is_htmx()`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
async fn plants(request: HttpRequest) -> Response {
|
||||
let list = html! { ul { li { "Tomato" } li { "Pepper" } } };
|
||||
if request.is_htmx() {
|
||||
HtmxResponse::new(list).into_response()
|
||||
} else {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Plants"))
|
||||
.with_child(Html::with(move |_| list.clone()))
|
||||
.render()
|
||||
.await
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`is_htmx()` lee la cabecera `HX-Request` que HTMX añade a sus peticiones. El trait
|
||||
`HtmxRequestExt` también ofrece `hx_target()`, `hx_trigger_id()`, `is_boosted()`... para leer las
|
||||
demás.
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
struct Clock;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Clock {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx]
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(home))
|
||||
.route("/time", web::get(time))
|
||||
}
|
||||
}
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Clock"))
|
||||
.with_child(
|
||||
Button::plain(Lc::n("What time is it?"))
|
||||
.with_prop(PropsOp::set(hx::GET, "/time"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "#time")),
|
||||
)
|
||||
.with_child(Html::with(|_| html! { p id="time" { "Not asked yet." } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn time(request: HttpRequest) -> HtmxResponse {
|
||||
let mut cx = Context::new(request);
|
||||
let mut badge = Badge::info(Lc::n(Utc::now().format("%H:%M:%S UTC").to_string()));
|
||||
HtmxResponse::new(badge.render(&mut cx).await)
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&Clock).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
1. Arranca la aplicación y abre <http://localhost:8080>.
|
||||
2. Pulsa el botón: la hora aparece en una etiqueta, sin recargar.
|
||||
3. En las herramientas de desarrollo del navegador (pestaña *Red*), la petición a `/time` lleva la
|
||||
cabecera `HX-Request: true` y la respuesta es una sola etiqueta `<span>`.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Cargar contenido bajo demanda](htmx-load.md): al pulsar, al cargar la página o al hacerse
|
||||
visible.
|
||||
- [Probar rutas y componentes](testing.md): cómo probar una ruta de HTMX sin navegador.
|
||||
- [HTML por la red: por qué HTMX](../explanation/htmx.md).
|
||||
Loading…
Add table
Add a link
Reference in a new issue