Module

middleware.inject

HTML injection middleware.

Injects a snippet (e.g. a<script> tag) into every text/html response before a configurable target string (default:</body>).

Useful for live-reload scripts, analytics, debug toolbars, or any markup that should appear on every page without modifying templates.

Classes

HTMLInject 2
Middleware that injects HTML content into text/html responses. Only affects ``Response`` objects w…

Middleware that injects HTML content into text/html responses.

Only affectsResponse objects whose content_typecontains text/html. StreamingResponse and SSEResponseare passed through unchanged.

When full_page_only isTrue, the snippet is injected only when the before target string is found in the response body. WhenFalse(the default), the snippet is appended at the end if the target string is absent.

Usage::

app.add_middleware(HTMLInject(
    '<script src="/__reload.js"></script>',
    before="</body>",
))

Methods

Internal Methods 2
__init__ 3
def __init__(self, snippet: str, *, before: str = '</body>', full_page_only: bool = False) -> None
Parameters
Name Type Description
snippet
before Default:'</body>'
full_page_only Default:False
__call__ 2 AnyResponse
Inject the snippet into HTML responses.
async
async def __call__(self, request: Request, next: Next) -> AnyResponse
Parameters
Name Type Description
request
next
Returns
AnyResponse
AlpineInject 1
HTMLInject that skips when Alpine is already present in the page. Checks for ``data-chirp="alpine"…

HTMLInject that skips when Alpine is already present in the page.

Checks fordata-chirp="alpine"in the response body before injecting. This prevents double-loading when chirp-ui'sapp_shell_layout.html (or any other source) has already included Alpine.

Methods

Internal Methods 1
__call__ 2 AnyResponse
async
async def __call__(self, request: Request, next: Next) -> AnyResponse
Parameters
Name Type Description
request
next
Returns
AnyResponse
ViewTransitionCssDebugWarning 1
Log when the response body uses View Transition CSS but VT injection is off. Only runs in debug bu…

Log when the response body uses View Transition CSS but VT injection is off.

Only runs in debug builds (seecompiler._collect_builtin_middleware). Helps catchview-transition-name / @view-transitionin templates while AppConfig.view_transitions is False, which disables HTMX global VT.

Methods

Internal Methods 1
__call__ 2 AnyResponse
async
async def __call__(self, request: Request, next: Next) -> AnyResponse
Parameters
Name Type Description
request
next
Returns
AnyResponse