Home

Awesome

asgi-htmx

Build Status Coverage Package version

HTMX integration for ASGI applications. Works with Starlette, FastAPI, Quart -- or any other web framework supporting ASGI that exposes the ASGI scope. Inspired by django-htmx.

Table of contents

Installation

NOTE: This is alpha software. Please be sure to pin your dependencies.

pip install asgi-htmx==0.1.*

Quickstart

First, ensure HTMX is installed.

For example, download a copy of htmx.min.js, add it to your static files, then add the script tag to templates:

<script src="{{ url_for('static', path='/js/htmx.min.js') }}" defer></script>

Now, install HtmxMiddleware onto the ASGI app:

You can now access scope["htmx"] (an instance of HtmxDetails) in endpoints:

# `HtmxRequest` makes code editors type-check `request.scope["htmx"]`
from asgi_htmx import HtmxRequest as Request

from .resources import templates

async def home(request: Request):
    template = "home.html"
    context = {"request": request}

    if (htmx := request.scope["htmx"]):
        template = "partials/items.html"
        context["boosted"] = htmx.boosted  # ...

    return templates.TemplateResponse(template, context)

See examples for full working example code.

API Reference

HtmxMiddleware

An ASGI middleware that sets scope["htmx"] to an instance of HtmxDetails (scope refers to the ASGI scope).

app = HtmxMiddleware(app)

HtmxDetails

A helper that provides shortcuts for accessing HTMX-specific request headers.

htmx = HtmxDetails(scope)

HtmxRequest

For Starlette-based frameworks, use this instead of the standard starlette.requests.Request so that code editors understand that request.scope["htmx"] contains an HtmxDetails instance:

from asgi_htmx import HtmxRequest as Request

async def home(request: Request):
    reveal_type(request.scope["htmx"])  # Revealed type is 'HtmxDetails'

License

MIT