Recipes
Expanded rows survive a list refresh
pub fn markup(orders: &[Order]) -> String {
let mut html = String::new();
for order in orders {
let key = format!("open{}", order.id);
html.push_str(&format!(
r#"<button type="button" data-state-toggle="{key}">#{id}</button><div data-state-show="{key}">…details…</div>"#,
id = order.id,
));
}
html
}<section id="orders"{{ orders_attrs }}> <!-- render_object("orders", &[Render, StateRead, StateWrite]) -->
<div id="orders-list">{{ list }}</div>
{{ refresh }} <!-- render_trigger("orders", Components, Some("#orders-list"), &[]) -->
</section>The list is replaced as a whole, and the expanded rows stay expanded. open{id} is made only from a numeric id, so it needs no escaping; anything containing user text must be escaped.
Forms: no lost input on validation failure
<form{{ form_attrs }}>
<input name="name" data-state-bind="name" value="{{ customer.name }}">
<input name="email" data-state-bind="email" value="{{ customer.email }}">
{{ cg_button("Save", type="submit", attrs={"data-linker-call": "save", "data-linker-args": "form"}) }}
</form>When Linker validation fails the form isn't redrawn, and the runtime draws the field errors. The successful save path must clear the state, or after the redraw the old input overwrites the new values from the server:
Ok(LinkerResponse::ok()
.then(Action::toast("success", "Saved"))
.then(Action::state_clear("customerForm"))
.then(Action::new(
"render.fragment",
json!({ "target": "#customer-form", "name": "customer.form", "fresh": true }),
).map_err(laravel::Error::msg)?))Dependent fields
<select name="method" data-state-bind="method">
<option value="pickup">Pickup</option>
<option value="delivery">Delivery</option>
</select>
<div data-state-is="method=delivery">…address fields…</div>For a plain comparison, use data-state-is. For real derived values (shipping cost depending on the amount, say), let Linker compute them and return data.
One value shared across objects
<span data-state-text="@cartCount">0</span>The @ prefix uses a global key; permissions still come from the enclosing object. Use it sparingly, and name it so it's obviously shared.
@ only works in data-state-* attributes. Linker's data and the state.set action always write into a namespace (.data("@cartCount", 3) is stored as objectName:@cartCount, not the global cartCount). So for shared values the server updates, use a fixed object name: write with Action::state_set("cart", "count", 3), and read it wherever it's needed inside a render object named cart.
Two calculators on one page
let all = [Allow::Render, Allow::StateRead, Allow::StateWrite];
view("calc", data! {})
.with_html("calc_a", Html::raw(runtime::render_object("calcA", &all).render(&[])))
.with_html("calc_b", Html::raw(runtime::render_object("calcB", &all).render(&[])));<section{{ calc_a }}>{% include "partials/calculator.html" %}</section>
<section{{ calc_b }}>{% include "partials/calculator.html" %}</section>Components inside fragments
Fragment functions return Html, so they can build components directly:
pub async fn render(input: RenderInput) -> laravel::Result<Html> {
let status = Badge::new("Paid").color(Color::Success).icon("check").render();
let edit = Button::new("Edit")
.variant(Variant::Outline)
.attributes(runtime::render_trigger("order.form", RenderMethod::Components, Some("#detail"), &[]))
.render();
Ok(Html::raw(format!("<div class=\"flex gap-2\">{}{}</div>", status.as_str(), edit.as_str())))
}The example project's src/cg/clock.rs puts a Badge in a fragment the same way.
Showing server messages as toasts
runtime::render_trigger("clock", RenderMethod::Toast, None, &[])Toast adds a new notification node each time and needs no target.
Code review checklist
- [ ] Every block using
data-state-*/ render fragments is inside a render object - [ ] The allow list grants only the
Allowvalues that are used - [ ] The
paramssent to the server are picked explicitly, not the whole state - [ ] Fragment functions validate every param themselves, and every interpolated value is
escaped - [ ] No fragment outputs private, user-specific data
- [ ] The successful save path clears state
- [ ] Hand-written
subscribe()calls are cleaned up withoff() - [ ] No passwords, files or amounts in state