Skip to main content

Block

Trait Block 

Source
pub trait Block:
    Send
    + Sync
    + 'static {
Show 16 methods // Required methods fn type_name(&self) -> &'static str; fn verbose_name(&self) -> &'static str; fn fields(&self) -> Vec<BlockField>; // Provided methods fn icon(&self) -> Option<&'static str> { ... } fn group(&self) -> Option<&'static str> { ... } fn description(&self) -> Option<&'static str> { ... } fn collapsed(&self) -> bool { ... } fn default_value(&self) -> Option<Value> { ... } fn version(&self) -> u32 { ... } fn template(&self) -> Option<&'static str> { ... } fn label_format(&self) -> Option<&'static str> { ... } fn preview_value(&self) -> Option<Value> { ... } fn preview_template(&self) -> Option<&'static str> { ... } fn extra_context( &self, _value: &Value, _ctx: &BlockRenderCtx<'_>, ) -> Map<String, Value> { ... } fn render( &self, value: &Value, ctx: &BlockRenderCtx<'_>, ) -> Result<String, BlockError> { ... } fn migrate(&self, _from: u32, value: Value) -> Result<Value, BlockError> { ... }
}
Expand description

One type of node that can sit in a WidgetKind::Stream list.

Three required methods, four optional with defaults, and render/migrate have generic default impls. Implementors mostly just describe their shape and let the defaults do the heavy lifting.

§Minimal impl

ⓘ
use rustango_cms::{Block, BlockField};
use rustango_cms::widget::WidgetKind;

pub struct HeadingBlock;

impl Block for HeadingBlock {
    fn type_name(&self) -> &'static str { "heading" }
    fn verbose_name(&self) -> &'static str { "Heading" }
    fn icon(&self) -> Option<&'static str> { Some("title") }
    fn fields(&self) -> Vec<BlockField> {
        vec![BlockField::widget("text", "Text", WidgetKind::Text)]
    }
}

rustango_cms::register_block!(HeadingBlock);

Required Methods§

Source

fn type_name(&self) -> &'static str

Wire-format identifier — the type key in the JSON envelope (e.g. "heading"). Must be globally unique across the process; duplicate registrations panic at boot.

Source

fn verbose_name(&self) -> &'static str

Human-readable label shown in the admin picker + per-block header chip.

Source

fn fields(&self) -> Vec<BlockField>

Structural shape. Each entry is rendered as one form input (or sub-stream) in the admin editor and one entry in the block’s stored value dict.

Provided Methods§

Source

fn icon(&self) -> Option<&'static str>

Material-symbols icon name shown next to the block’s label in the picker + the per-block header. None → generic “widgets” glyph.

Source

fn group(&self) -> Option<&'static str>

Picker grouping. Same string ⇒ same visual section in the “+ Add block” popover. None ⇒ “Other” bucket.

Source

fn description(&self) -> Option<&'static str>

One-line description shown in the picker tile tooltip + the “what does this block do” hint when the editor hovers over an entry. None ⇒ no tooltip.

Source

fn collapsed(&self) -> bool

Whether new instances of this block start collapsed in the admin editor. Default false (expanded). Set true for blocks whose default value already reads well in the collapsed header so the editor scrolls less when the page has many of them.

Source

fn default_value(&self) -> Option<Value>

Initial value when a fresh instance of this block is inserted into a stream. None ⇒ the editor opens a blank instance (every field empty). Useful for blocks whose canonical entry state isn’t the all-empty shape (e.g. a Heading with level=h2 pre-selected).

The returned JSON must match the block’s Self::fields shape — a dict keyed by field name. The admin editor merges this dict with the empty defaults on insert.

Source

fn version(&self) -> u32

Schema version. Bump when this block’s fields() changes in a way that requires migrating stored JSON. Versions on disk that differ from this trigger Self::migrate on every load.

Source

fn template(&self) -> Option<&'static str>

Optional override of the default render template (blocks/<type_name>.html). Useful for blocks that share a template with another (e.g. multiple heading-level variants).

Source

fn label_format(&self) -> Option<&'static str>

Collapsed-state header template. When non-None, the admin editor replaces the default static Self::verbose_name label with this string, substituting {field_name} tokens against the current block value. Useful so a Heading block in its collapsed state shows the actual heading text instead of just “Heading”.

Example: Some("{text} (H{level})") on a heading block renders as Welcome (H2) when value = {text: "Welcome", level: "2"}.

The format string is also stamped onto the rendered block as data-label-format= so the stream editor JS can live-update the header when the author edits any field.

Source

fn preview_value(&self) -> Option<Value>

Sample value used to render a preview thumbnail inside the block-picker tile. When set, the admin pre-renders this block with the sample value (via Self::preview_template or the regular block template) and stashes the resulting HTML on each PickerOption. Editors get a “what does this look like” glimpse before they insert the block.

Source

fn preview_template(&self) -> Option<&'static str>

Optional override of the template used for Self::preview_value rendering. Defaults to Self::template (the same template used for the public-side render). Useful when the block’s real template emits markup that needs heavy CSS / context to look right but a tiny mock preview is enough.

Source

fn extra_context( &self, _value: &Value, _ctx: &BlockRenderCtx<'_>, ) -> Map<String, Value>

Augments the Tera ctx with derived values (e.g. a layout-string → grid-span map) before the block’s template renders. Default returns an empty map. Keys cannot shadow the framework’s own ctx entries (value, block_type, computed) — those are stamped last.

Example:

ⓘ
fn extra_context(&self, value: &Value, _: &BlockRenderCtx) -> serde_json::Map<String, Value> {
    let layout = value.get("layout").and_then(Value::as_str).unwrap_or("1");
    let spans = match layout {
        "2-1" => vec!["col-span-2", "col-span-1"],
        "1-2" => vec!["col-span-1", "col-span-2"],
        _ => vec!["col-span-1"],
    };
    serde_json::json!({ "spans": spans }).as_object().unwrap().clone()
}
Source

fn render( &self, value: &Value, ctx: &BlockRenderCtx<'_>, ) -> Result<String, BlockError>

Render this block’s value to HTML. The default walks Self::fields, renders each into a Tera context map, and renders the registered template. Override only for blocks that bypass the field walker entirely.

§Errors

Tera failures + shape mismatches surface as BlockError::TemplateRender / BlockError::Shape.

Source

fn migrate(&self, _from: u32, value: Value) -> Result<Value, BlockError>

Migrate stored JSON from an older version() to the current one. The registry calls this stepwise — once per integer version between the stored value’s version and self.version() — so authors write single-version-step migrators only.

The default is a no-op; blocks that change their schema override this.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§