Documentation
On this page
Install Cirth for FastAPI + Jinja2
FastAPI is known for JSON APIs, and it renders HTML too: Jinja2Templates
turns a template into a response, and StaticFiles serves a folder as it
is. This guide is for an app that sends pages to a browser; an API that only
returns JSON has no stylesheet to link. The base Jinja template supplies the
document head for every page that extends it, so Cirth loads once globally.
Five steps: install, add the file, mount the files and the templates, link it from the base template and check it.
1 Install #
pip install "fastapi[standard]" jinja2
2 Add the file #
mkdir -p static/css templates
curl -o static/css/cirth.min.css \
https://cdn.jsdelivr.net/npm/@cirthcss/cirth@0.17.0/dist/cirth.min.css
3 Mount the files and the templates #
In main.py:
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
async def subscribe(request: Request):
return templates.TemplateResponse(
request=request, name="subscribe.html", context={"name": "FastAPI"}
)
4 Link it from the base template #
templates/base.html links the file through url_for, which knows where
/static is mounted:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}My site{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', path='/css/cirth.min.css') }}">
</head>
<body>
<main class="container">{% block content %}{% endblock %}</main>
</body>
</html>
and templates/subscribe.html extends it:
{% extends "base.html" %}
{% block content %}
<article>
<header><h1>Hello, {{ name }}</h1></header>
<form method="post" action="/subscribe">
<label>
Email
<input type="email" name="email" required>
</label>
<button type="submit">Subscribe</button>
</form>
</article>
{% endblock %}
Run it with fastapi run main.py; fastapi dev main.py reloads on every
change while you work.
5 Check it #
Put this forced-dark region in a page or component that uses the global stylesheet:
<section data-theme="dark">
<article>
<p>Dark, whatever the system scheme is.</p>
</article>
</section>
Run the app, then open
the page while the system uses a light theme. A dark article proves that
Cirth loaded and that data-theme="dark" is working. It remains dark when
the system switches to a dark theme.
Customization covers the --cirth-* properties; set
yours in a stylesheet in static/css, linked after Cirth. Package and builds lists the classless,
scoped and print entry points. Return to Framework guides
for another stack.