Table rows and dom.repeat
When every row of a list looks the same, there's no need to send the whole HTML back each time. Instead:
- Put one hidden reference template row on the page (
data-linker-ref-dom). - A Linker method returns the built-in action
dom.repeat, carrying only data. - The browser clones the template, fills in
%field%, and puts the rows into the table.
mermaid
flowchart LR
T["Hidden template row<br/><tr data-linker-ref-dom>"] --> C["Clone × N"]
D["dom.repeat<br/>{ ref, items }"] --> C
C --> F["Fill %field%<br/>(textContent / setAttribute)"]
F --> P["Insert into tbody"]
P --> B["Dispatch cg:rendered → bind the new rows' data-linker-call"]In the Rust version this is also the standard way to build lists that depend on the user: fragment functions can't see the user, Linker methods can (context.user).
A complete example: a budget list
Template
html
<div{{ budget_attrs }}> <!-- every hook must be inside the mount point -->
<p><span data-linker-ref-meta="budget:total">0</span> rows,
page <span data-linker-ref-meta="budget:current_page">1</span></p>
<table>
<thead>
<tr><th>Year</th><th>Month</th><th>Amount</th><th></th></tr>
</thead>
<tbody>
<!-- 1. Hidden template: never shown, never bound -->
<tr class="hidden" data-linker-ref-dom="budget">
<td>%year%</td>
<td>%month%</td>
<td class="amount">%amount%</td>
<td>
<button data-linker-call="delete"
data-linker-args='{"id": %id%}'
data-linker-confirm="Delete this row?"
data-linker-confirm-danger>Delete</button>
</td>
</tr>
<!-- 2. Empty state (optional). When there is data, add hidden on the server to avoid a flash -->
<tr data-linker-ref-empty="budget"{% if total > 0 %} class="hidden"{% endif %}>
<td colspan="4">No data</td>
</tr>
</tbody>
</table>
<button data-linker-call="show" data-linker-args='{"page": 2}'>Next page</button>
<!-- 3. First-render data: embedded in the page, saving a round trip -->
{{ seed }}
</div>Component
rust
#[derive(Default, Serialize, Deserialize)]
pub struct BudgetList {
page: u64,
}
impl LinkerComponent for BudgetList {
const ALIAS: &'static str = "budget";
const METHODS: &'static [&'static str] = &["show", "delete"];
async fn call(&mut self, context: &LinkerContext, method: &str, args: Args) -> laravel::Result<LinkerResponse> {
let user = User::find_or_fail(context.user.parse::<i64>()?).await?;
match method {
"show" => {
let page = args.get("page").and_then(|v| v.as_str()?.parse().ok().or(v.as_u64())).unwrap_or(1);
self.page = page.clamp(1, 10_000);
}
"delete" => {
let Some(id) = args.get("id").and_then(Value::as_i64) else {
return Ok(LinkerResponse::validation([("id", "The id is missing.")]));
};
let budget = Budget::find_or_fail(id).await?;
user.authorize(BudgetPolicy::delete, &budget).await?;
budget.delete().await?;
}
_ => unreachable!("METHODS lists every method"),
}
let items = page(&user, self.page).await?;
Ok(LinkerResponse::ok().then(
Action::new("dom.repeat", json!({ "ref": "budget", "items": items, "mode": "replace" }))
.map_err(laravel::Error::msg)?,
))
}
}
/// Shared by the seed and dom.repeat, so both always have the same shape.
pub async fn page(user: &User, page: u64) -> laravel::Result<Value> {
const PER_PAGE: u64 = 20;
let query = Budget::query().filter(Budget::user_id.eq(user.id));
let total = query.clone().count().await?;
let rows = query
.order_by(Budget::year.desc())
.offset((page - 1) * PER_PAGE)
.limit(PER_PAGE)
.get()
.await?;
Ok(json!({
"data": rows.iter().map(|b| json!({ "id": b.id, "year": b.year, "month": b.month, "amount": b.amount })).collect::<Vec<_>>(),
"total": total,
"current_page": page,
"last_page": total.div_ceil(PER_PAGE).max(1),
}))
}(Budget and BudgetPolicy are illustrative; follow the Laravel for Rust documentation for the query builder. A complete runnable version is in the searchable list tutorial.)
Handler
rust
pub async fn index(user: Authenticated<User>) -> laravel::Result<View> {
let mount = linker::mount::<BudgetList, User>(&user, linker::Args::new()).await?;
let first = budget::page(&user, 1).await?;
Ok(view("budget.index", data! { total => first["total"].as_u64().unwrap_or(0) })
.with_html("budget_attrs", Html::raw(mount.html()))
.with_html("seed", Html::raw(seed("budget", &first))))
}seed() is in the next section.
First-render data and seeds
PHP has @linkerRefSeed; in Rust, output the same tag yourself:
rust
/// `<script type="application/json" data-linker-ref-seed>`: JSON that can't close its tag.
fn seed(name: &str, items: &impl serde::Serialize) -> String {
let json = serde_json::to_string(items)
.unwrap_or_else(|_| "null".into())
.replace('<', "\\u003c")
.replace('>', "\\u003e")
.replace('&', "\\u0026");
format!(
r#"<script type="application/json" data-linker-ref-seed="{}">{json}</script>"#,
cg_component::escape(name)
)
}- When the mount point is bound, the browser reads this script and runs
dom.repeatonce on the template with the same name (applied only once). <>&must be replaced: a</script>in the data would close the tag.- Put it inside the mount point.
dom.repeat arguments
| Argument | Type | Description |
|---|---|---|
items | array | An array, or a paginator shape (data + total + current_page…) |
ref | string? | The template name, matching data-linker-ref-dom |
mode | string? | replace (default) / append / prepend |
replaceremoves everything at the same level except the template and empty state, including rows the server rendered at first.appendsuits "load more" and infinite scrolling.- There's no
Action::repeatshortcut; useAction::new("dom.repeat", json!({...})), and the argument types are checked on the Rust side.
Markers
| Marker | Effect |
|---|---|
data-linker-ref-dom="name" | The template. Clones lose this attribute, the hidden attribute and the hidden class, and get data-linker-ref-clone |
data-linker-ref-empty="name" | Shown with 0 items, hidden when there is data |
data-linker-ref-meta="name:field" | Fills a top-level field of items (total, current_page, last_page…) |
data-linker-ref-allow="data-x aria-y" | Extra plain-text attributes that may be filled |
data-linker-ref-seed="name" | First-render data (a JSON script, applied once) |
%field%, %a.b% | The row's value (can be nested) |
%lang:group.key% | A translation from window.trans (cg-lang.json); :field is replaced with the row's value |
Where placeholders can go
The whole process never goes through the HTML parser. Positions are allow-listed:
| Position | Check |
|---|---|
Text in td th span div p a button label li option h1–h6… | As text; emptied inside script style textarea svg |
title alt placeholder value label datetime aria-label… | Plain text |
colspan rowspan min max step aria-value* | Removed if not a number |
class | Each word may contain only letters, digits and - _ : / . [ ] |
href (<a> <area>), src (<img> <source> <audio> <video> <track>) | Only http(s), mailto, tel and relative URLs |
data-linker-args | The value is JSON-encoded; removed if the result isn't valid JSON |
For any other attribute (id, name, style, on*, data-linker-call…), a placeholder removes the whole attribute with a console warning.
dom.repeat or a fragment?
dom.repeat | render.fragment | |
|---|---|---|
| Transfer | JSON data only | A whole block of HTML |
| Row structure | Every row the same | Rows can differ, with conditional blocks |
| Depends on the user | Yes (Linker sees the user) | No (fragment functions can't see the user) |
Template logic ({% if %}) | Not inside rows | Yes |
| Without JS | Only the empty state and server-rendered rows | The first render works as usual |
| Good for | Big tables, pagination, load more, live updates, personal data | Complex public cards, help sections |
Common mistakes
- The template isn't inside the mount point →
dom.repeatonly looks for templates inside the mount point. - The empty state flashes → add
hiddenon the server based ontotal. - Buttons in cloned rows don't respond → just put
data-linker-callon the template; after insertioncg:renderedbinds it automatically. Don't put it indata-linker-ref-allow. - Using
%id%as an element id →idisn't allow-listed and is removed entirely. Use adata-*attribute and add it todata-linker-ref-allow. Action::newreturnsErr→itemsisn't an array or object,modeisn't a string, or there's an unknown argument.