Templates¶
Kuí supports Jinja2 templates for rendering HTML responses.
Setup¶
from kui.asgi import Kui, Jinja2Templates
templates = Jinja2Templates("templates") # Directory path
app = Kui(templates=templates)
Jinja2Templates accepts one or more directory paths:
It also supports package-relative paths using "package:path" syntax:
Rendering Templates¶
Use TemplateResponse to render a template:
from kui.asgi import TemplateResponse, request
@app.router.http.get("/")
async def homepage():
return TemplateResponse(
"index.html",
{"request": request, "title": "Home", "items": [1, 2, 3]},
)
The second argument is the template context dictionary. Always include request if you need to access request data in the template.
Template Configuration¶
Jinja2Templates creates a Jinja2 Environment with:
autoescape=True— HTML escaping enabled by defaultFileSystemLoaderorPackageLoaderdepending on path format
Access the underlying Jinja2 environment via the .env attribute:
templates.env.globals["app_name"] = "My App"
templates.env.filters["custom_filter"] = my_filter_func
Requirements¶
Jinja2 must be installed:
Kuí checks for Jinja2 availability at import time and disables template support if not found.