Refusals: _firewall(), _reject(), _forbidden(), _error() htmx

Keep an endpoint for htmx only (_firewall()), or end a request with 503, 403 or 500 and no page.

_class('htmx')->_firewall()
_class('htmx')->_reject()
_class('htmx')->_forbidden()
_class('htmx')->_error()

Options

OptionMeaning
_firewall()Returns true for an htmx request; any other request gets _reject().
_reject()503 Service Unavailable, graphics off, end of request (yf_api::_reject()).
_forbidden()403 Forbidden.
_error()500 Internal Server Error.

Example

Code

$hx = _class('htmx');
// only an htmx request reaches _firewall() here: a plain one would get the 503 at once
if ($hx->_wants_fragment() && ($_GET['hx'] ?? '') === 'firewall' && $hx->_firewall()) {
    return $hx->_result('<span class="text-success">Passed _firewall(): this was an htmx request.</span>');
}
asset('htmx');
return '<button type="button" class="btn btn-default btn-outline-secondary" hx-get="' . _prepare_html(url('/@object/htmx/errors')) . '" hx-vals=\'{"hx": "firewall"}\' hx-target="#docs-ref-hx-fw">Call an htmx-only endpoint</button> '
    . '<span id="docs-ref-hx-fw"></span>';

Notes

  • htmx does not swap 4xx / 5xx answers by default: handle htmx:responseError or answer 200 with a message when the user should see it.
  • These end the request at once: call them before any output.

See also: htmx/request, htmx/cache