Conditional Rendering for HTMX vs Direct Requests #77
-
I'm trying to implement endpoints that return:
I'm currently using conditional logic in components to check @dataclass
class DemoComponent:
def htmy(self, context: Context) -> Component:
request = CurrentRequest.from_context(context)
is_htmx = "HX-Request" in request.headers
content = html.div("This is the content of the demo page")
if is_htmx:
return content # Just the content. Will be swapped in by HTMX.
else:
return BasePage(content=content) # Return full page layout. Is this the intended approach, or does FastHX have a built-in decorator/pattern for automatically handling HTMX vs full page rendering without manual header checking in each component? The goal is having the same URL work for both HTMX navigation and direct browser access. By the way: thank you @volfpeter for your work on this library, as well as https://github.com/volfpeter/htmy! I've never had an easier time developing with another stack. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
Hi, First of all, thanks for your kind comment! I'm actually considering adding it to the readme as a user testimonial 🙂 Now to the business. Answering such questions is tricky with HTMX, because we're dealing with both the backend, the frontend, and interactions between the two, and a lot of the context (for example API and component architecture) is not available. Here are some ideas for your code example/use-case:
In my projects, I always separate "page" routes (which normally have no business logic, I hope I managed to help a bit. If you need more help, my usual recommendation is to get in touch for consulting. |
Beta Was this translation helpful? Give feedback.
Hi,
First of all, thanks for your kind comment! I'm actually considering adding it to the readme as a user testimonial 🙂
Now to the business. Answering such questions is tricky with HTMX, because we're dealing with both the backend, the frontend, and interactions between the two, and a lot of the context (for example API and component architecture) is not available.
Here are some ideas for your code example/use-case:
ComponentSelector
, in your specific case to a customRequestComponentSelector
implementation (similar toComponentHeader
). The only drawback here is that you must use…