【13.0】Fastapi中的Jinja2模板渲染前端页面

【一】创建Jinja2引擎

# 必须模块
from fastapi import  Request
# 必须模块
from fastapi.templating import Jinja2Templates

# 创建子路由
application = APIRouter()

# 创建前端页面配置
templates = Jinja2Templates(directory='./coronavirus/templates')

# 初始化数据库引擎对象
Base.metadata.create_all(bind=engine)

【二】前端页面书写

  • 前提
    • 引入必要的第三方UI库
    • semantic.min.css
    • jquery-3.5.1.min.js
    • semantic.min.js
<!DOCTYPE html>
<html lang="en">
<head>
    <title>新冠病毒疫情跟踪器</title>
    <link rel="stylesheet" href="{{ url_for('static', path='/semantic.min.css') }}">
    <script src="{{ url_for('static', path='/jquery-3.5.1/jquery-3.5.1.min.js') }}"></script>
    <script src="{{ url_for('static', path='/semantic.min.js') }}"></script>
</head>

<body>
<div class="ui container">
    <h2></h2>
    <h1 style="text-align: center">新冠病毒疫情跟踪器</h1>
    <h2></h2>

    <button id="filter" style="float: left" type="submit" class="ui button alert-secondary">过滤</button>

    <div class="ui input">
        <label for="city"></label><input id="city" type="text" placeholder="城市" value="">
    </div>

    <button id="sync" style="float: right" type="submit" class="ui button primary">同步数据</button>

    <table class="ui celled table">
        <thead>
        <tr>
            <th>城市</th>
            <th>日期</th>
            <th>累计确诊数</th>
            <th>累计死亡数</th>
            <th>累计痊愈数</th>
            <th>更新时间</th>
        </tr>
        </thead>
        <tbody>
        {% for d in data %}
        <tr>
            <td>{{ d.city.province }}</td>
            <td>{{ d.date }}</td>
            <td>{{ d.confirmed }}</td>
            <td>{{ d.deaths }}</td>
            <td>{{ d.recovered }}</td>
            <td>{{ d.updated_at }}</td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
</div>
</body>
<script>
    $(document).ready(function () {
        $("#filter").click(function () {
            const city = $("#city").val();
            window.location.href = "http://" + window.location.host + "/coronavirus?city=" + city;
        });
        $("#sync").click(function () {
            $.get("{{ sync_data_url }}", function (result) {
                alert("Message: " + result.message);
            });
        });
    });
</script>
</html>
  • 页面显示
    • http://127.0.0.1:8999/coronavirus/

image-20230930212251011

  • 过滤功能

image-20230930212712321

posted @ 2023-10-01 15:33  Chimengmeng  阅读(286)  评论(0编辑  收藏  举报
/* */