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