Skip to content

HTMX Attributes as Response Headers #712

@benpate

Description

@benpate

In the spirit of HATEOAS, I'm proposing that we expand the HX- headers that htmx supports to include a number of the existing features currently available only as attributes. This would give more power and control to the server when determining how HTML fragments are swapped into the DOM, allowing the server to change the behavior of certain links without programming it into the browser ahead of time.

HTMX Attributes as Response Headers

Ajax requests could be updated to look for the following headers. If present, these values could override any settings inherited in the HTML DOM.

Attribute Notes
HX-Swap Especially useful when setting locations like BeforeEnd, AfterBegin, etc.
HX-Target This may be supported by Hx-Retarget, but without hx-swap its usefulness is limited.
HX-Push-URL This could possibly be accomplished by updating with the existing HX-Push Response Header.

There are already a couple of Request Headers that mimic hx- attribute features. As this list grows, it would be nice to keep the naming consistent between these two domains.

Example Use Case

I have a number of modal dialogs in my application that display "edit" forms, confirm deletions, and more. The links to open them currently look something like this:

<a 
    hx-get="/record123/modal-confirm-delete" 
    hx-push-url="false" 
    hx-target="body" 
    hx-swap="beforeend"
    >Delete</a>

The link above returns the HTML code to confirm the user's delete request, which is then swapped into the end of the <body> without changing the URL. All good. But, a little long.

To shortcut this, I've written a small _hyperscript behavior that simplifies the boilerplate down to a more manageable. I've experimented with using an hx-swap-oob for these instead, but it still requires extra attributes that I'd like to simplify. Here is the behavior:

<a hx-get="/record123/modal-confirm-delete" _="install AsModal">Delete</a>

But, for "reasons" in my app, I'd like the dynamically generated HTML to determine if it shows up as a modal, or if it swaps into the page normally. In this best-case world, the code would simply look like this

<a hx-get="/record123/modal-confirm-delete">Delete</a>

Using this form, the additiona "missing" attributes would be included in the response headers, meaning that the server could determine how the link is to be viewed without coding it into the HTML template ahead of time.

Yes?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions