Skip to content

HtmxResponseHeader objects

The HtmxResponseHeader provides a toolset to properly assemble the data for each of the response headers that HTMX supports.

HTMX Response Headers

A powerful secondary tool in HTMX is a suite of response headers that cause or modify behaviors when the response is processed by HTMX.

HX-Location

allows you to do a client-side redirect that does not do a full page reload but rather issues an HTMX request. This can be a simple request that replaces the <body> or a fully described swap.

HX-Push-Url

pushes a new url into the history stack.

HX-Redirect

can be used to do a client-side redirect to a new location.

HX-Refresh

if set to “true” the client-side will do a full refresh of the page.

HX-Replace-Url

replaces the current URL in the location bar.

HX-Reswap

allows you to specify how the response will be swapped. See hx-swap for possible values.

HX-Retarget

a CSS selector that changes the target of the content update to a different element on the page. Overrides an existing hx-target on the triggering element.

HX-Reselect

a CSS selector that allows you to choose which part of the response is used to be swapped in. Overrides an existing hx-select on the triggering element

Trigger Headers

The trigger headers all share the same syntax. They can be simply an event name or they can be a JSON data set that includes both the event name and additional data for the event to use.

HX-Trigger

allows you to trigger client-side events.

HX-Trigger-After-Settle

allows you to trigger client-side events after the settle step.

HX-Trigger-After-Swap

allows you to trigger client-side events after the swap step.

How to use response headers in your code.

  1. Build the headers using an HtmxResponseHeaders object.
  2. Export the headers into '#attached' => 'http_header' on the render array.
$htmxHeaders = new HtmxResponseHeaders();
$htmxHeaders->trigger('recalculateSummary')
$build['#attached']['http_header'] = $htmxHeaders->toArray()

If your render array already has existing headers, then merge your HTMX headers in after they are built.

$build['#attached']['http_header'] => [
  ['Your-Header', 'Your-Value', TRUE]
];

$htmxHeaders = new HtmxResponseHeaders();
$htmxHeaders->trigger('recalculateSummary');
$addedHeaders = $htmxHeaders->toArray();
$build['#attached']['http_header'] = NestedArray::mergeDeep($build['#attached']['http_header'], $addedHeaders));