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

6 KiB

Usar componentes

Objetivo: construir la interfaz con los componentes que trae PageTop: crearlos, configurarlos, anidarlos y ajustar sus clases y atributos sin tocar su código.

Un componente es una pieza de interfaz con su propio HTML (y, si los necesita, sus estilos y scripts). Se crea con un constructor, se configura con métodos with_*() encadenados y se añade a una página o a otro componente.

# use pagetop::prelude::*;
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
    Page::new(request)
        .with_child(
            Block::new()
                .with_title(Lc::n("What's new"))
                .with_child(Html::with(|_| html! { p { "Version 2 is here." } }))
                .with_child(Button::anchor(Lc::n("Download"), "/downloads")),
        )
        .render()
        .await
}

Los componentes no se pintan al crearlos, sino al renderizar la página. Por eso pueden adaptarse al idioma de cada visitante, al tema activo o al usuario conectado.

El catálogo básico

PageTop trae un conjunto de componentes que funcionan con cualquier tema. La lista completa, con sus constructores, está en el catálogo de componentes.

Componente Para qué sirve
Html Marcado puntual con html!
Container Agrupa componentes en un <div>, <section>, <header>...
Block Bloque con título y contenido
Intro Portada de bienvenida con título, eslogan y botón
Button Botones y enlaces con aspecto de botón
Badge Etiquetas pequeñas de estado
Image Imágenes, también responsive
Brand Logotipo y nombre del sitio
Breadcrumb Migas de pan
Messages Avisos al usuario
Dialog Ventanas de diálogo
Flex, Grid Maquetación
Nav, Navbar, Dropdown Navegación
Form y sus campos Formularios
Table, Pager Tablas y paginación
PoweredBy Pie con el crédito «Funciona con PageTop»

Contenedores

Container agrupa varios componentes. Elige la etiqueta con el constructor:

# use pagetop::prelude::*;
# fn f() -> Container {
Container::section()
    .with_id("team")
    .with_child(Html::with(|_| html! { h2 { "The team" } }))
    .with_child(Block::new().with_title(Lc::n("Ana")))
    .with_child(Block::new().with_title(Lc::n("Luke")))
# }

Container::new() genera un <div>; también están header(), main(), section(), article() y footer().

Botones

# use pagetop::prelude::*;
# fn f() -> Vec<Button> { vec![
// A link that looks like a button.
Button::anchor(Lc::n("See the catalog"), "/catalog"),
// A form submit button, with style and intent.
Button::submit(Lc::n("Save"))
    .with_style(button::Style::Solid(Intent::Success))
    .with_size(button::Size::Large),
// An outline button, disabled.
Button::plain(Lc::n("Delete"))
    .with_style(button::Style::Outline(Intent::Severe))
    .with_disabled(true),
# ] }

Intenciones

Muchos componentes reciben una Intent: el significado del color, no el color. El tema decide cómo se ve cada una.

Intent Significado
Primary Acción principal
Neutral Sin énfasis
Info Información
Success Éxito o confirmación
Warning Advertencia
Severe Error o acción peligrosa
# use pagetop::prelude::*;
# fn f() -> Vec<Badge> { vec![
Badge::success(Lc::n("Active")),
Badge::warning(Lc::n("Pending")),
Badge::neutral(Lc::n("Archived")),
# ] }

Imágenes

# use pagetop::prelude::*;
# fn f() -> Image {
Image::with(image::Source::responsive("/static/img/cover.jpg"))
    .with_alternative(Lc::n("View of the harbour at dawn"))
# }

El origen (image::Source) decide cómo se muestra: plain() a su tamaño, responsive() ajustada al ancho disponible y thumbnail() como miniatura.

Identificadores, clases y estilos

Todos los componentes aceptan with_id() y with_prop(). Con PropsOp añades clases, atributos o estilos sin tocar el componente:

# use pagetop::prelude::*;
# fn f() -> Block {
Block::new()
    .with_id("featured")
    .with_prop(PropsOp::add_classes("block-highlight shadow"))
    .with_prop(PropsOp::set("data-section", "home"))
    .with_prop(PropsOp::add_style("border-radius", "8px"))
# }

Para márgenes y rellenos hay tipos propios, Margin y Padding, con unidades tipadas:

# use pagetop::prelude::*;
# fn f() -> Block {
Block::new()
    .with_prop(Margin::new().with_bottom(UnitValue::RelRem(2.0)))
    .with_prop(Padding::new().with_all(UnitValue::Px(16)))
# }

Mensajes al usuario

Page acumula avisos en su contexto y el componente Messages los muestra:

# use pagetop::prelude::*;
async fn saved(request: HttpRequest) -> Result<Markup, ErrorPage> {
    let mut page = Page::new(request).with_child(Messages::new());
    page.context()
        .push_message(MessageLevel::Info, Lc::n("Your changes have been saved."));
    page.render().await
}

Una portada en un minuto

Intro monta una página de presentación con un solo componente:

# use pagetop::prelude::*;
async fn landing(request: HttpRequest) -> Result<Markup, ErrorPage> {
    Page::new(request)
        .with_child(
            Intro::custom()
                .with_title(Lc::n("Urban Garden"))
                .with_slogan(Lc::n("Grow your city"))
                .with_button(Some((Lc::n("Start here"), Route::from("/guide"))))
                .with_child(
                    Block::new()
                        .with_title(Lc::n("What is it?"))
                        .with_child(Html::with(|_| html! { p { "A network of community gardens." } })),
                ),
        )
        .render()
        .await
}

Siguiente