htmx icon indicating copy to clipboard operation
htmx copied to clipboard

htmx history issue with alpine <template x-teleport="#id"> tag

Open nikalexis opened this issue 3 years ago • 0 comments

Using htmx with this config: <meta name="htmx-config" content='{"useTemplateFragments":true}'>

Using alpine V3, let's say that you want to make a teleport inside a htmx get div:

<div id="page_header"></div>
<div id="page">
<!-- This alpine teleport updates the panel header with an appended h1-->
<template x-teleport="#panel_header">
    <h1>Page title of main page</h1>
</template>
Some page content here. Go to <a hx-get="/another_page" hx-target="#page">another page</a>.
</div>

When the <a> object is clicked, htmx removes the template object, alpine removes the teleported <h1>, htmx requests the new content, a new teleport gets in place and alpine places the new <h1> object in #panel_header_left div. Everything works fine with the new get and the new teleport!

But, when you hit the back button, the history of htmx runs and make a copy all DOM objects, including <h1> and <template x-teleport> objects. As a result when the new DOM gets in place, alpine realizes that a new teleported template got in place and you end up with 2 <h1> headers (alpine teleport can only append items). The first placed <h1> was never removed by alpine, because I guess the first <template x-teleport> was never removed also (just replaced by htmx?). Alpine thought the history replaced template as a new one.

I know this a corner case, but htmx and alpine transport feature gives great power, so I thought this worth an opened issue. I don't have a clew, how htmx could handle these case. Maybe by doing a special copy for the template objects, but unfortunately I have no idea how this could be implemented.

PS: I found a workaround for now by refreshing the page on every history back trigger with the following config: <meta name="htmx-config" content='{"useTemplateFragments":true, "refreshOnHistoryMiss": true, "historyCacheSize": 1}'>

nikalexis avatar Oct 14 '22 06:10 nikalexis