Skip to content

Your first render fragment ​

Goal: an expandable block where "Refresh" replaces the whole HTML and the expanded state stays as it was. No JS written at all.

The PHP version calls this renderBlade: a controller becomes callable through the CanRenderCallSafely trait. Rust has no class lookup, so instead you register functions by name, and the registry is the allow list.

1. The fragment function ​

src/cg/hello.rs:

rust
use cg_component::escape;
use cg_component::runtime::render::RenderInput;
use laravel::view::Html;

pub const NAME: &str = "hello";

/// The fragment's HTML. The page's first render and later redraws share this function.
pub fn markup(rendered_at: &str) -> String {
    format!(
        r#"<p>Rendered on the server at: {}</p>
<button type="button" data-state-toggle="open">Expand / collapse</button>
<div data-state-show="open">Whether this is expanded lives in client state, not in the DOM.</div>"#,
        escape(rendered_at)
    )
}

pub async fn render(_input: RenderInput) -> laravel::Result<Html> {
    Ok(Html::raw(markup(&now())))
}

pub fn now() -> String {
    laravel::now().strftime("%H:%M:%S").to_string()
}
  • It returns laravel::Result<Html>. Html::raw doesn't escape again, so you must escape every value you insert (or build the HTML from components, which escape).
  • RenderInput has method, params, target and url; this function doesn't need them.

2. Register it ​

src/cg/mod.rs:

rust
pub mod hello;   // public, because the handler uses markup for the first render

pub fn register() {
    // …existing registrations
    cg_component::runtime::render::register(hello::NAME, hello::render);
}

POST /{prefix}/render answers 422 for any name that isn't registered, for the same reason PHP refuses any controller without the trait.

3. The page handler ​

src/http/handlers/hello.rs:

rust
use cg_component::runtime::render::RenderMethod;
use cg_component::runtime::{self, Allow};
use cg_component::{Button, Component};
use laravel::prelude::*;
use laravel::view::{Html, View};

use crate::cg::hello;

pub async fn show() -> View {
    let object = runtime::render_object("helloBox", &[Allow::Render, Allow::StateRead, Allow::StateWrite]);
    let refresh = Button::new("Refresh")
        .attributes(runtime::render_trigger(hello::NAME, RenderMethod::Components, Some("#hello-box"), &[]))
        .render();

    view("hello", data! {})
        .with_html("object_attrs", Html::raw(object.render(&[])))
        .with_html("first", Html::raw(hello::markup(&hello::now())))
        .with_html("refresh", refresh)
}

Add route.get("/hello", hello::show); to src/routes/web.rs.

  • render_object declares that this block may Render and read and write state; the name helloBox is the namespace.
  • render_trigger produces data-cg-event="renderBlade", data-render-name, data-render-method and data-render-target; .attributes(...) adds them to the button.
  • The first render calls markup directly, saving a round trip (PHP's @renderInline).

4. The template ​

resources/views/hello.html:

html
{% extends "layouts/site.html" %}

{% block content %}
<section{{ object_attrs }} data-state-init="open=false">
    <div id="hello-box">{{ first }}</div>
    {{ refresh }}
</section>
{% endblock %}

data-state-init only writes when the key doesn't exist yet, so a redraw doesn't overwrite what the user did.

5. Try it ​

  1. Click "Expand" → the content appears.
  2. Click "Refresh" → the time changes (the HTML was replaced as a whole), and the content is still expanded.
  3. Paste this into the console:
js
document.addEventListener('cg:state', e => console.log(e.detail.key, '→', e.detail.value));

Every toggle prints helloBox:open → true/false.

  1. Click "Refresh" twice within the same second: the second response is {"unchanged": true, …}, with no html, and the DOM doesn't change.

Why it works ​

Click "Expand"     → state helloBox:open = true → data-state-show displays it
Click "Refresh"    → POST /{prefix}/render { name: "hello", method: "components", target: "#hello-box", key, fingerprint }
Server             → uses up a one-time render token → calls hello::render → returns { html, key: new token, fingerprint }
Browser            → replaces #hello-box's innerHTML → rescans and binds
New data-state-show → reads helloBox:open → true → still displayed

The state never went to the server with the request, and didn't need to. The full flow is in the Render fragments overview.

Next: the Tutorials, or dig into Render fragments.