# NAME

Dancer2::Plugin::HTMX - HTMX request classification, response headers and fragment rendering for Dancer2

# VERSION

version 0.0001

# SYNOPSIS

    use Dancer2;
    use Dancer2::Plugin::HTMX;

    # One URL, two representations: the full page normally, just the rows
    # when htmx swaps them in. Vary includes the headers used to choose.
    get '/inventory' => sub {
        hx_template 'inventory/index', { rows => rows() }, { fragment => 'inventory/_rows' };
    };

    post '/containers' => sub {
        my $errors = validate( body_parameters );
        if (%$errors) {
            status 422;    # swapped only if htmx is configured to (see below)
            return hx_template 'containers/_form', { errors => $errors };
        }
        my $id = create_container( body_parameters );
        hx_trigger { 'container-created' => { id => $id } };
        hx_redirect "/containers/$id", 303;    # or 200 + HX-Redirect for htmx
    };

# DESCRIPTION

A thin layer over the htmx 2 request/response header contract
([https://htmx.org/reference/](https://htmx.org/reference/)). It classifies requests, sets response
headers with validation, and chooses between a full document and a fragment.
Templates, authorization and business logic stay in your application.

Requires Perl 5.28 or later.

HTMX request headers are hints sent by the client. Use them to choose a
representation, never to decide what a user may see or do.

# KEYWORDS

## is\_htmx

True when the request carries `HX-Request: true`. Adds
`HX-Request` and `HX-History-Restore-Request` to `Vary`.

## htmx\_request

Returns a hashref describing the request's htmx headers. `is_htmx`,
`boosted` and `history_restore` are Perl truth values and are true only
when the corresponding header contains the literal string `true`.
`current_url`, `prompt`, `target`, `trigger` and `trigger_name` are
the header values as sent, or `undef` when absent. On Perl 5.28,
`JSON::MaybeXS` encodes the truth values as `1` and `""`.

Adds the same `Vary` fields as ["is\_htmx"](#is_htmx). If application code uses other
request headers to choose a cacheable response, include those headers in
`Vary` as well.

## hx\_template $view, \\%tokens, \\%options

Renders `$view` with the configured layout for ordinary, boosted
(`hx-boost`) and history-restore requests. Other htmx requests render without
a layout. `fragment => $other_view` in
`%options` renders a different template for the fragment case. Other options
pass through to Dancer2's `template`. Always adds
`Vary: HX-Request, HX-History-Restore-Request, HX-Boosted` (merged with any existing
`Vary`; `Vary: *` is left alone).

## hx\_redirect $url, $status

For htmx requests: status 200, `HX-Redirect: $url`, empty body (a full page
load in the browser). Otherwise Dancer2's `redirect` (default 302). Either
way the route ends here. Root-relative URLs get the app's mount point, as
with `redirect`.

## hx\_location $path | \\%spec, $status

For htmx requests, returns HTTP 200 with `HX-Location` and an empty body.
The client makes an AJAX request to the destination. An options hash requires
`path` and accepts `target`, `source`, `event`, `handler`, `swap`,
`values`, `headers`, `select`, `push` and `replace`. Options must be
JSON-serializable. Unknown keys croak. Set `push` to `'false'` to skip
the history update, or supply a history URL with `push` or `replace`.

For ordinary requests, redirects to the path with `$status` (default 302).
A root-relative destination path gets the app's mount point. Either response
ends the route.

## hx\_refresh

For htmx requests, returns HTTP 200 with `HX-Refresh: true` and an empty body
to reload the current page. For ordinary requests, sends a 303 redirect to
the request's own URL, including its query string. Either response ends the
route.

## hx\_push\_url $url | 'false', hx\_replace\_url $url | 'false'

Set `HX-Push-Url` or `HX-Replace-Url`. Root-relative URLs get the app's
mount point. `'false'`, `0` and `''` suppress the history update.

## hx\_retarget $css\_selector, hx\_reselect $css\_selector, hx\_reswap $swap\_spec

Set `HX-Retarget`, `HX-Reselect` and `HX-Reswap`. `hx_reswap` checks that
the spec starts with an htmx swap style (`innerHTML`, `outerHTML`,
`textContent`, `beforebegin`, `afterbegin`, `beforeend`, `afterend`,
`delete`, `none`); modifiers such as `show:top` follow it.

## hx\_trigger $event | \\%events, after => 'receive' | 'swap' | 'settle'

Triggers client-side events through `HX-Trigger` (`receive`, the default),
`HX-Trigger-After-Swap` or `HX-Trigger-After-Settle`. `\%events` maps
event names to JSON-serializable details. In the browser, object properties
are exposed under `event.detail`. Scalars and arrays are available as
`event.detail.value`. A bare event name is sent as JSON `null`, which
htmx exposes as `event.detail.value` set to `null`.

Calls in one request merge into one JSON object per header. Later details
replace earlier ones for the same event and header. Event names can contain
ASCII letters, digits, `_`, `:`, `.` and `-`.

# ERRORS

Raw header values such as URLs, selectors and swap specs must be nonempty
printable ASCII strings. Percent-encode URLs that contain non-ASCII text.
Values in JSON headers support Unicode and are ASCII-escaped on the wire.
Invalid arguments croak.

# HTMX CONFIGURATION

htmx ignores response headers on 3xx responses, which is why the navigation
keywords answer htmx requests with 200.

By default htmx 2 does not swap 4xx or 5xx responses. To re-render a form
with its validation errors under status 422 and to omit `HX-Request` from
history restore requests, use this htmx configuration.

    <meta name="htmx-config" content='{
      "historyRestoreAsHxRequest": false,
      "responseHandling": [
        {"code": "204",    "swap": false},
        {"code": "[23]..", "swap": true},
        {"code": "422",    "swap": true},
        {"code": "[45]..", "swap": false, "error": true},
        {"code": "...",    "swap": false}
      ]}'>

`hx_template` renders a full page for `HX-History-Restore-Request: true`
regardless of `historyRestoreAsHxRequest`.

# SEE ALSO

[https://htmx.org/docs/](https://htmx.org/docs/), [https://htmx.org/reference/](https://htmx.org/reference/), [Dancer2::Plugin](https://metacpan.org/pod/Dancer2%3A%3APlugin).

# AUTHOR

D Ruth Holloway <ruth@hiruthie.me>

# COPYRIGHT AND LICENSE

This software is copyright (c) 2026 by D Ruth Holloway.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
