pagetop-website/doc/v0.6/es/src/how-to/actions.md
Manuel Cillero 1a41a456d4 ✨ 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.
2026-10-17 08:06:02 +02:00

3.5 KiB

Intervenir con acciones

Objetivo: cambiar lo que hace otra extensión (cómo se ve un componente, qué HTML genera, qué lleva cada página) sin tocar su código.

Una acción permite a una extensión intervenir en lo que hace otra sin tocar su código: ajustar un componente antes de pintarlo, retocar su HTML o añadir algo a todas las páginas.

Se declaran en actions() con la macro actions!. PageTop las registra una sola vez al arrancar.

1. Ajusta un componente antes de renderizarlo

BeforeRender<C> recibe el componente (mutable) y el contexto, justo antes de que se pinte. Por ejemplo, añadir una clase a todos los botones de la aplicación:

use pagetop::prelude::*;

pub struct RoundButtons;

#[async_trait]
impl Extension for RoundButtons {
    fn actions(&self) -> Vec<ActionBox> {
        actions![action::component::BeforeRender::<Button>::new(round)]
    }
}

fn round(button: &mut Button, _cx: &mut Context) {
    button.alter_prop(PropsOp::add_classes("rounded-pill"));
}

Para actuar sólo sobre un componente concreto, fíltralo por su identificador:

# use pagetop::prelude::*;
# fn highlight(button: &mut Button, _cx: &mut Context) {}
# fn f() -> Vec<ActionBox> {
actions![
    action::component::BeforeRender::<Button>::new(highlight).filter_by_referer_id("buy"),
]
# }

2. Retoca el HTML final

TransformMarkup<C> recibe el HTML ya generado y devuelve el nuevo. Si hay varias, se encadenan:

# use pagetop::prelude::*;
pub struct Marker;

#[async_trait]
impl Extension for Marker {
    fn actions(&self) -> Vec<ActionBox> {
        actions![action::component::TransformMarkup::<Block>::new(mark_block)]
    }
}

fn mark_block(_block: &Block, _cx: &Context, markup: Markup) -> Markup {
    html! {
        div class="marked-block" { (markup) }
    }
}

AfterRender<C> se ejecuta tras renderizar, por si sólo necesitas reaccionar (registrar algo, por ejemplo).

3. Interviene en todas las páginas

BeforeRenderBody y AfterRenderBody reciben la página entera. Así añade la extensión HTMX su script a todas las páginas:

# use pagetop::prelude::*;
pub struct Analytics;

#[async_trait]
impl Extension for Analytics {
    fn actions(&self) -> Vec<ActionBox> {
        actions![action::page::BeforeRenderBody::new(add_script)]
    }
}

fn add_script(page: &mut Page) {
    page.alter_assets(JavaScript::defer("/static/js/analytics.js"));
}

4. Decide el orden

Las acciones de un mismo tipo se ejecutan por peso (de menor a mayor; admite negativos) y, a igualdad de peso, por orden de registro:

# use pagetop::prelude::*;
# fn first(b: &mut Button, cx: &mut Context) {}
# fn f() -> Vec<ActionBox> {
actions![action::component::BeforeRender::<Button>::new(first).with_weight(-10)]
# }

Resumen

Acción Recibe Momento
component::BeforeRender<C> &mut C, &mut Context Antes de renderizar C
component::AfterRender<C> &mut C, &mut Context Después de renderizar C
component::TransformMarkup<C> &C, &Context, Markup Para sustituir el HTML de C
page::BeforeRenderBody &mut Page Antes de renderizar el <body>
page::AfterRenderBody &mut Page Después de renderizar el <body>

Siguiente