Skip to content

Starlette-Templates

Documentation | PyPI

Starlette-Templates serves Jinja templates, Markdown pages, and static assets through a Starlette app. A Jinja2 loader identifies the directories that contain your site, and StaticFiles resolves each request to a file in those directories. Templates render on each request, Markdown becomes HTML, and assets such as stylesheets and images are returned unchanged.

Why use Starlette-Templates

StaticFiles combines page rendering and asset serving in one mounted app. A ChoiceLoader lets application files override files supplied by a package, so a site can share a theme while keeping its own pages and assets. Static assets receive HTTP caching headers, while rendered pages can use request data and template globals.

Markdown layouts give written pages a shared HTML structure, and shortcodes let templates and Markdown reuse components through Jinja tags. When a page needs database results, it can declare named SQL queries alongside the markup that displays them; your application supplies the query runner that executes them.

For interactive pages, htmx fragments connect reusable templates to application events. A response can name a change, such as an updated cart, and return every affected fragment so the browser can update several parts of the page together.

Installation

pip install starlette-templates

Hello world example

Save the following app as app.py. It serves the site directory, with html=True allowing the root URL to resolve to an index page:

from jinja2 import FileSystemLoader
from starlette.applications import Starlette
from starlette.routing import Mount

from starlette_templates import StaticFiles

app = Starlette(
    routes=[
        Mount("/", StaticFiles(loader=FileSystemLoader("site"), html=True), name="site"),
    ]
)

Create site/index.html.jinja with a heading that uses the current request's hostname:

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

Install an ASGI server and run the app:

pip install uvicorn
uvicorn app:app --reload

Open http://localhost:8000/ to see the heading rendered with your hostname. Stylesheets, JavaScript, and images placed in the same directory are served unchanged with caching headers.

Choose your path

If you want to Read this
Serve assets, templates, and Markdown Static files
Add Markdown pages with a shared layout Markdown
Run a query from a page Named SQL queries
Turn a folder of snippets into Jinja tags Shortcodes
Update several parts of a page from one response HTMX fragments
Build HTML without a template file HTML in Python
Return an error as a page or as JSON Error handling
Look up a class or a function API reference

LLM context

For tools that read documentation as Markdown, llms.txt lists the available guides and llms-full.txt contains their full text.