Flask-HTMX

0.4.0 · active · verified Thu Apr 16

Flask-HTMX is a Flask extension that provides an easy API for working with HTMX from within a Flask request context. It simplifies integrating HTMX into Flask applications by enhancing the global request object and offering a specialized `make_response` function for HTMX-specific headers. The current version is 0.4.0, and the library maintains an active release cadence with regular updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates initializing Flask-HTMX and handling both regular and HTMX-triggered requests. It shows how to conditionally render partial content for HTMX requests and how to use `flask_htmx.make_response` to add HTMX-specific response headers, like `HX-Trigger`.

from flask import Flask, render_template
from flask_htmx import HTMX

app = Flask(__name__)
htmx = HTMX(app)

@app.route("/")
def home():
    if htmx:
        # HTMX request, return a partial template
        return render_template("partials/thing.html")
    # Normal browser request, return a full page
    return render_template("index.html")

@app.route("/click-me", methods=["POST"])
def click_me():
    # Example of using make_response for HTMX headers
    from flask_htmx import make_response
    return make_response("<span>Clicked!</span>", trigger={'myEvent': 'Data'})

view raw JSON →