Template Migration Guide
From string-concatenation handlers to TemplateResponse
Before:
@app.get("/page")
def page(name="World"):
html = "<h1>Hello " + str(name) + "</h1>"
return viperhttp.Response(body=html, content_type="text/html; charset=utf-8")
After:
@app.get("/page")
def page(name="World"):
return viperhttp.TemplateResponse(
"/www/page.html",
context={"name": name},
)
/www/page.html:
Recommended migration steps
- Move HTML strings to
/www/*.html. - Replace direct string concatenation with
TemplateResponse(path, context=...). - Keep
strict=True(default) during migration to catch missing keys early. - Add stable
ETagheaders for cacheable template routes. - Enable stream mode for larger payloads:
TemplateResponse(path, context=ctx, stream=True).
Common mapping patterns
- String interpolation:
"...%s..."->{{ value }} - Conditional fragments:
if ...: html += ...->{% if ... %}...{% endif %} - Repeated fragments:
loops ->
{% for item in items %}...{% endfor %} - Shared fragments:
duplicate HTML blocks ->
{% include "partial.html" %}
Validation checklist
- Run parser/runtime template tests.
- Confirm escaping behavior (
{{ ... }}) and explicit raw output (|safe). - Confirm strict mode failures for missing values.
- Confirm
stream=Truebehavior (chunked, optional gzip, cache headers).