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:
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::rawdoesn't escape again, so you mustescapeevery value you insert (or build the HTML from components, which escape). RenderInputhasmethod,params,targetandurl; this function doesn't need them.
2. Register it
src/cg/mod.rs:
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:
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_objectdeclares that this block mayRenderand read and write state; the namehelloBoxis the namespace.render_triggerproducesdata-cg-event="renderBlade",data-render-name,data-render-methodanddata-render-target;.attributes(...)adds them to the button.- The first render calls
markupdirectly, saving a round trip (PHP's@renderInline).
4. The template
resources/views/hello.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
- Click "Expand" → the content appears.
- Click "Refresh" → the time changes (the HTML was replaced as a whole), and the content is still expanded.
- Paste this into the console:
document.addEventListener('cg:state', e => console.log(e.detail.key, '→', e.detail.value));Every toggle prints helloBox:open → true/false.
- Click "Refresh" twice within the same second: the second response is
{"unchanged": true, …}, with nohtml, 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 displayedThe 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.