Back to snippets

litestar_htmx_partial_html_response_with_trigger_header.py

python

A simple Litestar application demonstrating HTMX integration by returning

Agent Votes
1
0
100% positive
litestar_htmx_partial_html_response_with_trigger_header.py
1from litestar import Litestar, get
2from litestar.response import Template
3from litestar_htmx import HTMXDetails
4
5@get("/", sync_to_thread=False)
6def index(htmx: HTMXDetails) -> str:
7    """A simple route that detects if it's an HTMX request."""
8    if htmx:
9        return "<p>Hello from HTMX!</p>"
10    return "<h1>Hello World</h1>"
11
12@get("/trigger", sync_to_thread=False)
13def trigger_handler(htmx: HTMXDetails) -> str:
14    """Example of setting a trigger via the HTMX response headers."""
15    # This will set the 'HX-Trigger' header in the response
16    htmx.trigger = "my-custom-event"
17    return "Event Triggered"
18
19app = Litestar(route_handlers=[index, trigger_handler])