htmx icon indicating copy to clipboard operation
htmx copied to clipboard

HX-boost but only replacing parts of the page

Open svezina opened this issue 3 years ago • 2 comments

Hi all,

Is there a way, while doing full page hx-boost requests, to get it to only change specific targets in the DOM, even though the response contains the whole page?

In other words, let's say I'm in this situation:

  • I don't want to convert all of my full page templates to partials in order to use hx-boost + hx-target. I just want to flip on the hx-boost and be done with it.
  • When the full page hx-boost request comes back, although it contains the whole page, along with menus, sidebars and everything, I only want it to only replace the content in specific DOM elements, say my #main div.

Is there a way to accomplish that? I couldn't find a way in the documentation.

This is something that can be done with Pjax. The Pjax library has an "elements" option that is the equivalent to hx-boost, but it also has a "selectors" option where you can give it a list of ids where the content has to be replaced.

Thanks!

svezina avatar Jul 23 '22 15:07 svezina

Hi there, have you tried hx-select ?

David-Guillot avatar Jul 23 '22 17:07 David-Guillot

Hi there, have you tried hx-select ?

I just did. Thanks for the help. I managed to get a bit further in the process. With a combination of hx-boost, hx-select and hx-disinherit, I was able to almost get the desired behavior:

<body hx-boost="true" hx-target="#main" hx-select="#main">
	<div id="stuff_i_dont_want_to_change" hx-disinherit="hx-select hx-target">
		<div id="my_open_chat_windows"></div>
		<div id="my_sidebar"></div>
	</div>
	<nav>
		<a href="/home/>Home</a>
		<a href="/page/>Page</a>
	</nav>
	<div id="#main">
	</div>
</body>

This worked mostly fine, but, unfortunately, when I used the back button, or did a refresh, the #main div would show for a millisecond and disappear.

By adding these meta tags in the head, I managed to get the reloads to work fine:

<meta name="htmx-config" content='{"historyCacheSize": 0, "refreshOnHistoryMiss": true}'>
<meta name="Cache-Control" content="no-cache">

But the back button still blanks my #main div. I'm going to keep trying but if anyone has tips and tricks I'd be curious.

Thanks

svezina avatar Jul 23 '22 23:07 svezina

Hmmm, that should be working. hx-select is the way to accomplish what you want.

1cg avatar Jan 06 '23 22:01 1cg

You just need to swap the outerHTML of #main in the response into the #main in the requesting page. Like this:

<body hx-boost="true" hx-target="#main" hx-select="#main" hx-swap="outerHTML">

croxton avatar Jan 16 '23 15:01 croxton