renderBlade Overview
Hand a block of HTML to the server to re-render, without losing what the user was in the middle of.
What the problem looks like
renderBlade asks the server for a Blade fragment and then replaces a container's innerHTML with it.
The upside: page logic stays in PHP and the front end needs no duplicate templates. The downside is a single one, but it hurts:
User expands row 3 → clicks "Refresh list" → the whole block of HTML is replaced → the expanded row collapses"Which rows are expanded" used to be stored in the DOM (a class, a hidden attribute, a JS variable). Replace the DOM and the memory goes with it.
The fix here: never put that state in the DOM in the first place.
Three roles
| Role | File | In one sentence |
|---|---|---|
| Object | resources/js/renderObject.js | A permission boundary for a block of DOM; its name is also the state namespace |
| State | resources/js/state.js | An in-memory key-value store that lives only in this tab, for this page load |
| Binding | resources/js/stateBind.js | Connects data-state-* to state; the DOM updates when a value changes |
Rendering itself is in resources/js/renderBlade.js. None of it is attached to window.
Five-minute start
1. Declare an object
Without this, every attribute below is refused (the console tells you why).
<section @renderObject('demoBox', ['state:read', 'state:write'])>
...
</section>'demoBox'is the name, and also the state namespace.- The second argument is the allow list:
render,state:read,state:write.
2. Add a toggle that remembers
<section @renderObject('demoBox', ['state:read', 'state:write'])
data-state-init="open=false">
<button type="button" data-state-toggle="open">Toggle</button>
<div data-state-show="open">
Whether this is shown is remembered
</div>
</section>So far, no JavaScript. Click the button → demoBox:open flips → the subscribed data-state-show updates hidden.
3. Make it survive a re-render
<section id="demo-box" @renderObject('demoBox', ['render', 'state:read', 'state:write'])>
<button type="button" data-state-toggle="open">Toggle</button>
<div data-state-show="open">Whether this is shown is remembered</div>
<button type="button"
data-cg-event="renderBlade"
data-render-name="{{ \App\Http\Controllers\DemoController::class }}"
data-render-target="#demo-box">Ask the server for this block again</button>
</section>The whole HTML is replaced → the new data-state-show reads open, which is still true, the moment it's bound → the block is expanded again automatically.
The allow list gained render: triggering a render is a separate action and must be granted separately.
On the server side, the controller uses the CanRenderCallSafely trait and implements renderCallSafely(). See Fetching Fragments.
One click, end to end
The key is the last two steps: after new content is inserted, bindings are always re-scanned, so "replace the HTML" and "keep the state" don't conflict.