You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I had a small use case on a website (let's call it www.example.com). I wanted to show there a list of blog posts that was nicely already part of a "sister website" blog.example.com. So I just did: <div hx-get="https://blog.example.com" hx-select=".posts" hx-trigger="load">loading...</div>
This worked otherwise nicely, but the relative links that were supposed to point to https://blog.example.com/my-post.html were now incorrect: https://www.example.com/my-post.html.
I couldn't find a way in Htmx to handle this situation, but I noticed that Htmx is aware of the source domain and path, so I was able to fix this with an extension like this:
/**
* Extension to fix loaded relative links to be relative
* to the source page instead of the current one.
*/
htmx.defineExtension('fix-relative-links', {
onEvent: function(name, evt) {
let isRelative = function(href) {
return !/^https?:\/\//i.test(href);
}
if (name === 'htmx:afterSwap') {
evt.detail.target.querySelectorAll('a[href]').forEach(function(a) {
let href = a.getAttribute('href');
if (isRelative(href)) {
a.href = evt.detail.pathInfo.requestPath + (href.startsWith('/') ? '' : evt.detail.pathInfo.responsePath) + href;
}
})
}
}
});
Is this kind of extension the correct way? Shall I make a PR?
If yes, are there any suggestions to improve it somehow?
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Hi,
I had a small use case on a website (let's call it www.example.com). I wanted to show there a list of blog posts that was nicely already part of a "sister website" blog.example.com. So I just did:
<div hx-get="https://blog.example.com" hx-select=".posts" hx-trigger="load">loading...</div>
This worked otherwise nicely, but the relative links that were supposed to point to
https://blog.example.com/my-post.html
were now incorrect:https://www.example.com/my-post.html
.I couldn't find a way in Htmx to handle this situation, but I noticed that Htmx is aware of the source domain and path, so I was able to fix this with an extension like this:
Is this kind of extension the correct way? Shall I make a PR?
If yes, are there any suggestions to improve it somehow?
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions