About 3 ways of using a link
How can the server distinguish between these 3 scenarios
Say, there is a /countries page
- User clicks a link: Server should respond with HTML fragment
- User ctrl+clicks a link: Server has to send the header+side bars+menus+ actual_html_content + footer
- Users pastes the link in address bar: Server should behave as in step 2
In scenario 1, can I add a header or cookie to indicate it is scenario 1 and not scenario 2 or 3?
Or, can I make "/countries_fragment" AJAX call , but push "/countries" to history? In this case, I have to write two endpoint functions on server side.
Looks like I found relevant info in "More Htmx Patterns" chapter. Still not clear if htmx can handle ctrl 2. need to try..
Here is an example in the docs that handles ctrl+click:
https://htmx.org/docs/#trigger-filters.
There's no need to listen to Ctrl click. When htmx issue a request, it adds a hxRequest header to the request. Server-side, you could use this to determine if the server has to send the whole page or fragment.
I made a project where I use this feature and add others behaviors using hx-headers.
https://github.com/alexandre-dos-reis/htmx-admin/blob/main/src/config/decorateRequest.ts#L23
https://github.com/alexandre-dos-reis/htmx-admin/blob/main/src/components/Layout.tsx#L26
As Alexandre said above, htmx will set the HX-Request header in every request it makes.
Opening a link with a ctrl+click or typing the URL in the address bar will behave just as a normal link, a normal request made by your browser, for which you wouldn't have this HX-Request header set.
So, simply check for that header server-side to determine in which scenario you're in!
I don't know your setup so maybe you are using boosting, in which case you don't need to do anything special I guess, otherwise you could it like this
<a href="/url" hx-get="/url" hx-target="#someTarget">...</a>
The hx-get will override the default behavior on click and issue a htmx request instead of moving the entire page, but a ctrl + click or a right click + "open in new tab" will work as a default link. On the server, you just check if the HX-Request header is defined or not