Chapter 13: Creating a Website with Templates
ASP.NET Core offers Razor Pages and MVC views. FastAPI does not include a page framework, but Starlette supports Jinja2 templates.
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
router = APIRouter()
templates = Jinja2Templates(directory="templates")
@router.get("/recipes", response_class=HTMLResponse)
def recipes_index(request: Request):
recipes = recipes_service.list_public_recipes()
return templates.TemplateResponse(
"recipes/index.html",
{"request": request, "recipes": recipes},
)
Python template guidance:
- Keep templates dumb. Business logic belongs in services.
- Use template inheritance for layout.
- Use partial templates for repeated UI.
- Escape by default. Jinja2 escapes HTML in configured environments.
- Add CSRF protection for browser forms.
If you want a deeply integrated server-rendered framework, Django is usually the better Python choice. FastAPI plus Jinja2 is excellent when your app is API-first and needs some server-rendered pages.