rustysan-sword 0.1.1

Blade-inspired HTML templates for Rust
Documentation
---
title: Components
weight: 6
---

A component can have its props declared as a Rust struct that serde fills from the tag, so a missing, misspelled or mistyped prop is an error at the tag instead of a blank in the output:

```rust
use rustysan_sword::{Component, ComponentError, Html, Sword};
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
enum Kind { Info, Warning }

#[derive(Deserialize, Serialize)]
struct Alert {
    kind: Kind,                // required
    #[serde(default)]
    dismissible: bool,
    #[serde(default)]
    label: String,
    message: Option<Html>,     // trusted markup, printed unescaped
}

impl Component for Alert {
    fn prepare(mut self) -> Result<Self, ComponentError> {
        if self.label.is_empty() {
            self.label = format!("{:?} alert", self.kind);
        }
        Ok(self)
    }
}

# let config = rustysan_sword::Config::default();
let sword = Sword::new(config).with_component::<Alert>("alert")?;
# Ok::<(), ComponentError>(())
```

`components/alert.sword.html` stays an ordinary template and reads each field as a variable; `<x-alert kind="warning" :dismissible="true" class="mt-4">…</x-alert>` fills the struct. A component with no registration is the anonymous component it always was.

- **Registration** happens while building the engine, returns a typed `ComponentError` (invalid or duplicate name, a type that is not a struct with named fields, `#[serde(flatten)]`, a field that cannot be a variable such as `slot`), and starts a fresh cache. Field names come from serde's own field list, so renames and defaults are honoured; use snake_case field names, because an attribute `kind-label` is matched as `kind_label`.
- **Input**: literal attributes are strings and `:name="expr"` keeps its type, with no coercion, so `size="3"` for a `u32` is an error that tells you to write `:size="3"`. Serde's message can quote the value, so keep it out of logs; Sword's own tracing records only the error kind.
- **Unknown attributes** are not passed to the struct; they become the `attributes` bag, as for anonymous components. Set `const STRICT_ATTRIBUTES: bool = true;` in the `Component` impl to make them a syntax error naming the attribute.
- **`prepare(self)`** runs after deserialization and may fill or reject values. It is synchronous and must not block.
- **`Html`** marks a field as trusted markup. A plain `String` is always escaped. Data cannot pose as trusted markup: the marker is a per-process random key.
- **`@props` is rejected** in a typed component's template; the struct is the single source of truth. `@aware` is unchanged and sees the attributes passed to the tag. Slots stay untyped template variables.
- **Dynamic components**: `<x-dynamic-component component="alert">` with a literal name is typed; a runtime name (`:component="name"`) that resolves to a typed component is an error, because the field list must be known when the template is translated.
- **Errors** read like other render errors, located at the tag: `page:12: <x-alert>: missing field `kind``.
- With the `laravel` feature, `SwordServiceProvider::new().component::<Alert>("alert")?` registers the same components. Each provider now owns its cache (128 entries by default, `with_cache_capacity` to change it, `cache_stats()` to read it), so applications in one process share nothing. The old process-wide `laravel::cache_stats()` function is gone.

Request data does not reach a component, so it cannot read the session or database; pass what it needs as props.