Skip to content

Starlette-Templates

This package extends Starlette with support for template-driven routing, form handling, and reusable UI components, built on Jinja2 and Pydantic.

Why does this exist? Starlette is a toolkit that offers building blocks for web apps. But common tasks like template routing, form validation, and UI reuse require significant boilerplate. This package streamlines those workflows by directly routing URLs to templates, validating form data with Pydantic, and enabling type-safe, reusable UI components built as Jinja templates. This makes applications easier to build, reason about, and scale.

Features

  • Serve HTML templates with file-based routing
  • Pydantic forms with validation and rendering
  • Reusable UI components using Jinja2 and Pydantic with type and validation safety
  • Static files with gzip compression and multi-directory support
  • JSON:API compliant error responses with custom error pages
  • ETag and Last-Modified headers with 304 Not Modified support

Installation

pip install starlette-templates

Quick Start

from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.routing import Mount
from jinja2 import PackageLoader

from starlette_templates.routing import TemplateRouter
from starlette_templates.middleware import JinjaMiddleware

app = Starlette(
    routes=[
        # File-based routing for the "templates" package directory
        Mount("/", TemplateRouter()),
    ],
    middleware=[
        # Configure Jinja2 environment for template autodiscovery
        Middleware(
            JinjaMiddleware,
            template_loaders=[PackageLoader("mypackage", "templates")],
        )
    ]
)

Create templates/index.html:

<!DOCTYPE html>
<html>
<head><title>My App</title></head>
<body><h1>Welcome to {{ request.url.hostname }}</h1></body>
</html>

Visit http://localhost:8000/ and your template will be rendered automatically.

Next Steps

LLM context

This documentation is available as an LLM-friendly markdown file: