惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google Online Security Blog
Google Online Security Blog
博客园_首页
酷 壳 – CoolShell
酷 壳 – CoolShell
Jina AI
Jina AI
博客园 - Franky
大猫的无限游戏
大猫的无限游戏
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美
V
V2EX
雷峰网
雷峰网
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
F
Full Disclosure
Y
Y Combinator Blog
V
V2EX - 技术
Attack and Defense Labs
Attack and Defense Labs
S
Security @ Cisco Blogs
Schneier on Security
Schneier on Security
Microsoft Azure Blog
Microsoft Azure Blog
SecWiki News
SecWiki News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The GitHub Blog
The GitHub Blog
量子位
PCI Perspectives
PCI Perspectives
S
Secure Thoughts
D
Darknet – Hacking Tools, Hacker News & Cyber Security
AWS News Blog
AWS News Blog
Blog — PlanetScale
Blog — PlanetScale
爱范儿
爱范儿
K
Kaspersky official blog
B
Blog
A
Arctic Wolf
Hacker News: Ask HN
Hacker News: Ask HN
L
LangChain Blog
T
Tor Project blog
P
Privacy & Cybersecurity Law Blog
Recent Announcements
Recent Announcements
宝玉的分享
宝玉的分享
The Register - Security
The Register - Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
L
Lohrmann on Cybersecurity
D
Docker
A
About on SuperTechFans
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
The Last Watchdog
The Last Watchdog
S
Security Affairs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Privacy International News Feed
Simon Willison's Weblog
Simon Willison's Weblog

博客园 - 全栈测试笔记

博文阅读密码验证 - 博客园 FastAPI系列(24):ORM操作之删除接口开发 单例模式管理模型客户端的几种实现方式 博文阅读密码验证 - 博客园 FastAPI系列(23):ORM操作之编辑接口开发 FastAPI系列(22):ORM之多对多查询记录 FastAPI系列(21):ORM之多对多添加记录 CC Switch配置模型 Claude Code安装 FastAPI系列(20):ORM添加表记录 FastAPI系列(19):ORM响应页面数据 博文阅读密码验证 - 博客园 FastAPI系列(18):ORM查询操作 FastAPI系列(17):ORM的迁移命令 FastAPI系列(16):ORM创建模型类 FastAPI系列(14):Jinja2模板语法之过滤器 FastAPI系列(13):Jinja2模板介绍、模板语法之变量渲染 FastAPI系列(12):响应模型参数 【汇总】FastAPI系列教程
FastAPI系列(15):Jinja2模板语法之控制结构
全栈测试笔记 · 2026-01-27 · via 博客园 - 全栈测试笔记

本系列汇总,请查看这里https://www.cnblogs.com/uncleyong/p/19503695

分支控制:if

image

jinja2中的if语句类似与Python的if语句,它也具有单分⽀,多分⽀等多种结构,不同的是,条件语句不需要使⽤冒号结尾,⽽结束控制语句,需要使⽤endif关键字。

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% if age >= 18 %}

<p>{{age}}:成年了</p>

{% else %}

<p>{{age}}:未成年</p>

{% endif %}


</body>
</html>

test_jinja2.py

import uvicorn
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates

app = FastAPI()

templates = Jinja2Templates(directory="templates")  # 实例化Jinja2对象,并将文件夹路径设置为以templates命令的文件夹


@app.get("/index")
def index(request: Request):  # TemplateResponse要求上下文包含Request类型的对象,这里需要传入
    age = 18

    return templates.TemplateResponse(
        "index.html",  # 模板文件
        {
            "age": age,
            "request": request,  # TemplateResponse要求上下文(context)中必须包含 "request" 键,value是Request类型对象
        },  # context上下文对象,一个字典
    )


if __name__ == '__main__':
    uvicorn.run("test_jinja2:app", port=8001, reload=True)

image

循环控制:for

jinja2中的for循环⽤于迭代Python的数据类型,包括列表,元组和字典。在jinja2中不存在while循环。

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


<!--使用 loop.index(从 1 开始-->
<ul>
    {% for hobby in hobbies %}
    <li>{{ loop.index }}:{{hobby}}</li>
    {% endfor %}
</ul>

<!--使用 loop.index0(从 0 开始)-->
<ul>
    {% for hobby in hobbies %}
    <li>{{ loop.index0 }}:{{hobby}}</li>
    {% endfor %}
</ul>

<!--使用 loop.revindex(倒序)-->
<ul>
    {% for hobby in hobbies %}
    <li>{{ loop.revindex }}:{{hobby}}</li>
    {% endfor %}
</ul>


</body>
</html>

test_jinja2.py

import uvicorn
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates

app = FastAPI()

templates = Jinja2Templates(directory="templates")  # 实例化Jinja2对象,并将文件夹路径设置为以templates命令的文件夹


@app.get("/index")
def index(request: Request):  # TemplateResponse要求上下文包含Request类型的对象,这里需要传入
    hobbies = ["coding", "swimming", "basketball"]

    return templates.TemplateResponse(
        "index.html",  # 模板文件
        {
            "hobbies": hobbies,
            "request": request,  # TemplateResponse要求上下文(context)中必须包含 "request" 键,value是Request类型对象
        },  # context上下文对象,一个字典
    )


if __name__ == '__main__':
    uvicorn.run("test_jinja2:app", port=8001, reload=True)

结果

image

分支嵌套循环:if嵌套for

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% if age >= 18 %}
<p>成年人:</p>
<ul>
    {%for name in person.adults%}
    <li>{{name}}</li>
    {% endfor %}
</ul>

{% else %}
<p>未成年人:</p>
<ul>
    {%for name in person.minors%}
    <li>{{name}}</li>
    {% endfor %}
</ul>

{% endif %}


</body>
</html>

test_jinja2.py

import uvicorn
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates

app = FastAPI()

templates = Jinja2Templates(directory="templates")  # 实例化Jinja2对象,并将文件夹路径设置为以templates命令的文件夹


@app.get("/index")
def index(request: Request):  # TemplateResponse要求上下文包含Request类型的对象,这里需要传入
    age = 18
    person = {"adults": ["李一", "李二", "李三"], "minors": ["王一", "王二"]}

    return templates.TemplateResponse(
        "index.html",  # 模板文件
        {
            "person": person,
            "age": age,
            "hobbies": hobbies,
            "request": request,  # TemplateResponse要求上下文(context)中必须包含 "request" 键,value是Request类型对象
        },  # context上下文对象,一个字典
    )


if __name__ == '__main__':
    uvicorn.run("test_jinja2:app", port=8001, reload=True)

结果

image

循环嵌套分支:for嵌套if

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h3>price高于100的书有:</h3>
<ul>
    {%for book in books%}
    {% if book.price > 100 %}
    <li>{{book.title}}</li>
    {% endif %}
    {% endfor %}
</ul>
<h3>price低于80的书有:</h3>
<ul>
    {%for book in books%}
    {% if book.price <80 %}
    <li>{{book.title}}</li>

    {% endif %}
    {% endfor %}
</ul>

</body>
</html>

test_jinja2.py

import uvicorn
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates

app = FastAPI()

templates = Jinja2Templates(directory="templates")  # 实例化Jinja2对象,并将文件夹路径设置为以templates命令的文件夹


@app.get("/index")
def index(request: Request):  # TemplateResponse要求上下文包含Request类型的对象,这里需要传入
    books = [{"title": "性能分析调优", "price": 90},
             {"title": "Python基础", "price": 50},
             {"title": "Python爬虫入门", "price": 60},
             {"title": "Python爬虫进阶", "price": 130},
             {"title": "Python进阶", "price": 120}]

    return templates.TemplateResponse(
        "index.html",  # 模板文件
        {
            "books": books,
            "request": request,  # TemplateResponse要求上下文(context)中必须包含 "request" 键,value是Request类型对象
        },  # context上下文对象,一个字典
    )


if __name__ == '__main__':
    uvicorn.run("test_jinja2:app", port=8001, reload=True)

结果

image