Templating & Static Files¶
Jinja2 integration and the static-file mount.
Jinja2Templates
¶
Jinja2 template engine integration.
Usage::
templates = Jinja2Templates(directory="templates")
@app.get("/page")
async def page(request: Request):
return templates.TemplateResponse("page.html", {"request": request, "name": "World"})
Any callables registered via @app.context_processor run before each
render; their returned dicts are merged into the template context
(caller's explicit context wins on collisions).
TemplateResponse
¶
TemplateResponse(name: str | Sequence[str], context: dict[str, Any], status_code: int = HTTP_200_OK, headers: dict[str, str] | None = None, *, media_type: str | None = None, background: Any = None) -> Response
Render a template and return a response, optionally overriding the content type and attaching a background task.
render
¶
Render a named template to a string (no Response wrapping).
Mirrors TemplateResponse but stops at the string stage so the
render_template(name, **ctx) helper can plug in
without building an HTMLResponse around the result.
stream
¶
Render a named template incrementally, yielding str chunks.
Mirrors render but returns a synchronous iterator of str chunks
instead of a fully-rendered string, so large templates can be
streamed to the client without buffering the whole body. Wrap it in
a StreamingResponse to return it from a handler.
Jinja's generator is lazy - chunks render as the response body is
consumed, which on the built-in server happens on a separate task
after the handler returns. Each chunk is therefore produced inside a
snapshot of the current context (current_app, g, request), so a
template that reads them or calls url_for resolves correctly during
emission instead of raising "working outside of application context".
The returned iterator is still synchronous, preserving the contract.
render_string
¶
Render a template from string.
render_async
async
¶
Asynchronously render a named template - Jinja enable_async.
Uses a separate async-enabled Environment (built lazily) so
{% include %}d templates with async I/O resolve without
blocking the loop. Filters/globals registered on app are
synced onto the async env too.
get_template
¶
Get a raw Jinja2 template object, resolving a fallback list to the first existing template.
render_template
¶
Render a named template against the current app.
Pulls the Jinja2Templates instance off current_app._templates
(set when the user constructs a Jinja2Templates(templates_dir) and
assigns it). Raises RuntimeError outside a request / app context.
Returns the rendered string; callers wrap in a Response themselves
if they need one.
render_template_string
¶
Render an inline string template against the current app.
Builds a transient Jinja2 environment when no Jinja2Templates is
bound on the app, so the helper works for one-off templates that
don't need a templates directory. Honours app-level filters /
globals / tests and context processors when the env is reachable
via app._templates.
stream_template
¶
Stream a named template against the current app, chunk by chunk.
Mirrors render_template but returns an iterator of str chunks
(Jinja's template.generate(...)) instead of a single string, so a
large response body is produced lazily. Pulls the Jinja2Templates
instance off current_app._templates; raises RuntimeError outside
a request / app context. Wrap the result in a StreamingResponse to
return it from a handler::
from veloce import StreamingResponse, stream_template
@app.get("/big")
async def big(request):
return StreamingResponse(stream_template("big.html", rows=rows))
StaticFiles
¶
Serve static files from a directory — all file I/O runs in executor.
Usage::
from veloce import Veloce
from veloce.contrib.staticfiles import StaticFiles
app = Veloce()
app.mount("/static", StaticFiles(directory="static"))