Skip to content

Instantly share code, notes, and snippets.

@travispaul
Created February 15, 2024 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save travispaul/27e652861df20d521f83bac651b18043 to your computer and use it in GitHub Desktop.
Save travispaul/27e652861df20d521f83bac651b18043 to your computer and use it in GitHub Desktop.
HX-Location
htmx.on('htmx:beforeRequest', event => {
const { detail: { etc: { values } } } = event
if (values) {
const { allowedPaths, notification } = values
const { pathname } = document.location
// If not at an allowed path don't redirect, just notify
if (allowedPaths.indexOf(pathname) === -1) {
event.preventDefault()
}
notify(notification)
}
})

The HX-Location response header looks something like this, the response body is empty:

hx-location: {
  "path":"/foo",
  "target":"#main",
  "select":"#content",
  "values": {
    "allowedPaths":["/foo/1"],
    "notification":"Foo 1 has been created"
   }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment