Skip to content

Asking the server for fragments ​

Server side: register fragment functions ​

PHP marks callable controllers with the CanRenderCallSafely trait. Rust has no class lookup, so you register functions by name: the registry is the allow list, and unregistered names get 422.

rust
use cg_component::escape;
use cg_component::runtime::render::{RenderInput, RenderMethod};
use laravel::view::Html;

pub const NAME: &str = "orders.results";

pub async fn render(input: RenderInput) -> laravel::Result<Html> {
    // params are untrusted input: pick the keys you need and validate them yourself
    let mode = match input.param("mode") {
        Some("detail") => "detail",
        _ => "results",
    };
    let page: u64 = input.param("page").and_then(|p| p.parse().ok()).filter(|p| *p >= 1).unwrap_or(1);

    Ok(Html::raw(format!(
        r#"<p data-mode="{}">Page {page}</p>"#,
        escape(mode)
    )))
}
rust
// src/cg/mod.rs
pub fn register() {
    cg_component::runtime::render::register(orders::NAME, orders::render);
}

RenderInput:

FieldTypeContents
methodRenderMethodComponents / Toast / Page / Isolated
paramsBTreeMap<String, String>The data-param-* values; null ones are dropped
targetOption<String>data-render-target
urlOption<String>The page the browser was on when it made the request

input.param("key") returns Option<&str>.

params are always strings

The server only guarantees that each param is a string of at most 2048 characters; target ≤ 128, url ≤ 2048, fingerprint ≤ 64. Business rules (types, ranges) are yours to check in the fragment function.

Fragment functions can't see the user

RenderInput has no request, session or logged-in user. Anyone who gets the page can use a render token to call any registered fragment with any params. So:

  • Don't output private, user-specific data in a fragment, and don't use an id from params to look up someone's data directly.
  • Leave user-specific content to Linker (it has context.user): return data or dom.repeat, or check permissions first and then return a render.fragment with no private data.

Producing HTML ​

Html::raw doesn't escape again. Three safe ways to build it:

rust
// 1. format! + escape: escape every interpolated value
Html::raw(format!("<p>{}</p>", escape(&name)))

// 2. Components: they escape text
Badge::new(name).color(Color::Info).render()

// 3. Render a MiniJinja template to a string (templates escape by default)

Browser side: four ways to trigger ​

1. On click: render_trigger ​

rust
let attrs = runtime::render_trigger(
    "orders.results",
    RenderMethod::Components,
    Some("#detail"),
    &[("mode", "detail"), ("id", &order.id.to_string())],
);
let link = Button::new(order.title.as_str()).attributes(attrs).render();

It produces data-cg-event="renderBlade", data-render-name, data-render-method, data-render-target and data-param-*. As in PHP, param names become kebab-case (pageSize → data-param-page-size) and the browser turns them back into camelCase when sending; empty-string params aren't output.

To keep navigation working without JS, put the attributes on an <a href="…"> (in the template, <a href="/orders/3"{{ attrs }}>); the runtime intercepts the click and uses a render fragment instead.

2. Automatically after load: render_auto ​

rust
let attrs = runtime::render_auto("clock", RenderMethod::Components, &[("pageSize", "10")]);
html
<div id="clock"{{ clock_attrs }}>Loading…</div>

The container must have an id; the fragment renders into it. Good for heavy content that may not be seen (tabs, collapsed sections) or that needs a loading skeleton.

3. Rendered in place by the server ​

PHP's @renderInline. Rust has no dedicated API: call the function that produces the HTML directly in the handler and put it on the page with with_html. Split "produce HTML" from "fragment function" into two functions so both share the same output:

rust
pub fn markup(page: u64) -> String { /* … */ }

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

// handler
view("orders", data! {}).with_html("results", Html::raw(orders::markup(1)))

4. Linker returns render.fragment ​

rust
Ok(LinkerResponse::ok().then(Action::render_fragment(
    "#results",
    "orders.results",
    json!({ "mode": "results", "page": "2" }),
)))

The business logic is in Linker, and redrawing is handed to render fragments. The browser forwards params with FormData, so every value goes through String(...) (null becomes an empty string) and the fragment always receives strings; passing strings from Rust avoids surprises. See Responses and actions.

Every trigger must be inside a render object that allows render.

Insertion modes (RenderMethod) ​

RenderMethodAttribute valueBehavior
ComponentscomponentsReplaces the target's innerHTML (the default); supports fingerprints
IsolatedisolatedInserts into shadow DOM, with isolated styles
ToasttoastAdds a new node each time (notifications)
PagepageReplaces the whole body and pushes history; the document stays, so client state is kept

Fragment fingerprints: no HTML when nothing changed ​

In components mode the server returns a fingerprint (the hex of the first 16 bytes of the HTML's SHA-256). The next time the browser asks for the same insertion point with the same target|name|method|params, it sends it back, and if the HTML is unchanged the server answers only { "unchanged": true }. That saves bytes and a DOM overwrite (focus and scroll position aren't lost).

  • It doesn't save server rendering: the HTML must be produced to know whether it changed.
  • When filters change (different params), the browser doesn't send the old fingerprint and always gets new HTML.
  • To force data-state-init to run again (resetting a form, restarting a wizard), give render.fragment fresh: true; when calling renderBlade directly, force: true. Rust's Action::render_fragment has no fresh parameter; use Action::new("render.fragment", json!({ "target": …, "name": …, "fresh": true })).
  • fresh doesn't clear state. To get back to an empty form, state.clear first, then fresh.
  • PHP uses xxh128 and Rust SHA-256; the browser only compares strings, so it makes no difference.

Fragments containing a Linker mount point are never unchanged

linker::mount produces a new instance uuid every time. Put the mount point on an outer element that isn't redrawn, and redraw the inner part.

Render tokens ​

Every request must carry a one-time key:

  • share_head issues one on every GET page, in <meta name="render-token">.
  • Each session keeps the most recent 16 (render::POOL); sending a used one again gets 419.
  • Every response (including unchanged) carries a new key, and the browser switches to it.
  • A page restored with back (bfcache) holds a used token, so the runtime first calls POST /{prefix}/render/token (60 per minute) for a fresh one, then renders.

Protocol ​

The request is multipart: name, method, target, url, params[key], fingerprint, key. The response:

json
{"method": "components", "name": "clock", "target": "#clock",
 "key": "<next token>", "fingerprint": "…", "html": "…"}
StatusWhen
200Success; no html when unchanged
404Wrong prefix
419The render token isn't in the session's pool (used or forged)
422Invalid fields, or the name isn't registered; same format as Laravel (message + errors)
500The fragment function returned Err

Events ​

Eventdetail
cg:renderedThe fields the server returned + { root } (no state); detail.unchanged is true when unchanged
cg:state{ key, value, previous }
cg:errorExceptions from rendering or subscribers