- 本文介绍简单的jinja2语法
- API
import uvicorn
from fastapi import FastAPI
from fastapi.requests import Request
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
app = FastAPI()
# 项目根目录下创建static与templates文件
app.mount("/static", StaticFiles(directory="static"))
templates = Jinja2Templates(directory="templates")
@app.get("/index")
def index(request: Request):
context = {
'request': request,
'name': 'xwl',
"age": 19,
"hobby": ["篮球", "足球"],
"info": {
"city": "北京",
"address": "昌平沙河"
}
}
return templates.TemplateResponse('index.html', context)
if __name__ == '__main__':
uvicorn.run(app, host="127.0.0.1", port=9001)
- 前端页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{name}} ({{age}})</h1>
<ul>
{% for item in hobby%}
<li>{{item}}</li>
{% endfor %}
</ul>
<div>
<ul>
{% for k,v in info.items()%}
<li>{{k}}{{v}}</li>
{% endfor %}
</ul>
</div>
<img src="/static/demo.png" style="width: 200px;">
</body>
</html>
标签:__,templates,FastAPI,app,jinja2,fastapi,import,模板
From: https://www.cnblogs.com/xwltest/p/18472983