第 8 章: FastAPI中的模板
本章概述
学习如何在FastAPI中使用模板引擎(Jinja2)返回HTML响应。
8.1 关于Jinja
Jinja2是一个功能强大的Python模板引擎,允许我们在HTML中嵌入Python代码。
8.2 Jinja入门
安装Jinja
pip install jinja2配置模板
from fastapi import FastAPI
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from starlette.requests import Request
app = FastAPI()
templates = Jinja2Templates(directory="templates")8.3 控制块
条件语句
{% if user %}
<h1>Hello {{ user.name }}!</h1>
{% else %}
<h1>Hello Stranger!</h1>
{% endif %}For循环
<ul>
{% for item in items %}
<li>{{ item.name }}: ${{ item.price }}</li>
{% endfor %}
</ul>8.4 过滤器
Jinja提供多种过滤器来处理数据:
<!-- 默认值 -->
{{ description|default("No description") }}
<!-- 转义 -->
{{ content|escape }}
<!-- 大写 -->
{{ name|upper }}
<!-- 小写 -->
{{ name|lower }}
<!-- 长度 -->
{{ items|length }}
<!-- 连接 -->
{{ list|join(", ") }}
<!-- 替换 -->
{{ text|replace("old", "new") }}8.5 设置变量
{% set title = "My Page" %}
<h1>{{ title }}</h1>8.6 块和宏
块(Blocks)
用于模板继承:
base.html:
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>page.html:
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
{% block content %}
<h1>Welcome!</h1>
{% endblock %}宏(Macros)
类似函数:
{% macro input(name, value='', type='text') %}
<input type="{{ type }}" name="{{ name }}" value="{{ value }}">
{% endmacro %}
{{ input('username') }}
{{ input('password', type='password') }}8.7 在FastAPI中使用Jinja
@app.get("/items/{id}", response_class=HTMLResponse)
async def read_item(request: Request, id: str):
return templates.TemplateResponse(
"item.html",
{
"request": request,
"id": id,
"items": [{"name": "Item 1"}, {"name": "Item 2"}]
}
)8.8 HTML任务列表示例
创建一个简单的任务列表应用:
main.py:
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
tasks = [
{"id": 1, "name": "Learn FastAPI"},
{"id": 2, "name": "Build an API"},
]
@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
return templates.TemplateResponse(
"index.html",
{"request": request, "tasks": tasks}
)templates/index.html:
<!DOCTYPE html>
<html>
<head>
<title>Task List</title>
</head>
<body>
<h1>Tasks</h1>
<ul>
{% for task in tasks %}
<li>{{ task.name }}</li>
{% endfor %}
</ul>
</body>
</html>
小结
在本章中,我们学习了: - ✅ 安装和配置Jinja2 - ✅ 使用控制块(条件、循环) - ✅ 使用过滤器 - ✅ 模板继承和块 - ✅ 宏(类似函数) - ✅ 在FastAPI中渲染HTML模板
在下一章中,我们将学习依赖项!