bigskysoftware / htmx

</> htmx - high power tools for HTML
https://htmx.org
Other
37.75k stars 1.28k forks source link

Add a "smart" swap style #1957

Open calind opened 11 months ago

calind commented 11 months ago

Currently, when writing components using templating engines, there are two ways to swap the entire component.

First - swap using outerHTML:

<div id="my-component" hx-get="{{ component_url }}" hx-swap="outerHTML">
    <div>component content</div>
</div>

Second - render only the component content on htmx requests:

{% if not request.htmx %} <div id="my-component" hx-get="{{ component_url }}"> {% endif %}
    <div>component content</div>
{% if not request.htmx %} </div> {% endif %}

The first falls short if you want to save some state on the wrapping div (eg. storing some state using data- attributes). The second does not have this issue, but you must always account for the htmx request in your templates which is less than ideal.

I propose adding a new swap strategy that swaps the innerHTML and omits the wrapping tag using some heuristics. For example, if the wrapping tag has the same name and ID as the target or maybe introduce a new hx-id attribute and do an inner swap if it matches.

This way, the first code will do the "right thing" (proven that defaultSwapStyle is set accordingly).

ghost commented 10 months ago

Hello, I would like to work on this issue.