Partial responses: _result(), _wants_fragment(), _vary() htmx
Answer an htmx request with a fragment of the page and end the request; other requests (and a history restore) get the whole page.
_class('htmx')->_result($r)
_class('htmx')->_wants_fragment()
_class('htmx')->_vary()Options
| Option | Meaning |
|---|---|
_wants_fragment() | True for an htmx request that is not the history restore htmx sends after a cache miss on Back (that one swaps the whole body). |
_result($html) | Prints the fragment with X-Robots-Tag: none and ends the request; EXIT_AFTER_RESULT = false (tests) returns it instead. |
_vary() | Adds Vary: HX-Request, HX-Target, HX-History-Restore-Request, so a cache never serves the fragment for the page or the other way round. |
Example
- Apples: 8
- Pears: 1
- Plums: 3
Code
$hx = _class('htmx');
$items = fn () => html()->list_group(['Apples: ' . random_int(1, 9), 'Pears: ' . random_int(1, 9), 'Plums: ' . random_int(1, 9)]);
if ($hx->_wants_fragment() && ($_GET['hx'] ?? '') === 'items') {
$hx->_vary();
return $hx->_result($items());
}
$hx->_vary();
asset('htmx');
return '<div id="docs-ref-hx-items">' . $items() . '</div>'
. '<button type="button" class="btn btn-default btn-outline-secondary" hx-get="' . _prepare_html(url('/@object/htmx/fragment')) . '" hx-vals=\'{"hx": "items"}\' hx-target="#docs-ref-hx-items">Reload the list only</button>';Notes
- In a module:
if (_class('htmx')->_wants_fragment()) { return _class('htmx')->_result(tpl()->parse('items_fragment', $data)); }then the full page; the layout never runs for the fragment. - table2 with
htmxdoes exactly this for requests whoseHX-Targetis its box.
See also: htmx/request, htmx/table2, htmx/reswap