控制代码块
控制代码块主要包含两个:
| - if/else if /else / endif |
| - for / endfor |
if语句
Jinja2 语法中的if语句跟 Python 中的 if 语句相似,后面的布尔值或返回布尔值的表达式将决定代码中的哪个流程会被执行:
| {%if user.is_logged_in() %} |
| <a href='/logout'>Logout</a> |
| {% else %} |
| <a href='/login'>Login</a> |
| {% endif %} |
过滤器可以被用在 if 语句中:
| {% if comments | length > 0 %} |
| There are {{ comments | length }} comments |
| {% else %} |
| There are no comments |
| {% endif %} |
循环
- 我们可以在 Jinja2 中使用循环来迭代任何列表或者生成器函数
| {% for post in posts %} |
| <div> |
| <h1>{{ post.title }}</h1> |
| <p>{{ post.text | safe }}</p> |
| </div> |
| {% endfor %} |
- 循环和if语句可以组合使用,以模拟 Python 循环中的 continue 功能,下面这个循环将只会渲染post.text不为None的那些post:
| {% for post in posts if post.text %} |
| <div> |
| <h1>{{ post.title }}</h1> |
| <p>{{ post.text | safe }}</p> |
| </div> |
| {% endfor %} |
- 在一个 for 循环块中你可以访问这些特殊的变量:
变量 | 描述 |
loop.index |
当前循环迭代的次数(从 1 开始) |
loop.index0 |
当前循环迭代的次数(从 0 开始) |
loop.revindex |
到循环结束需要迭代的次数(从 1 开始) |
loop.revindex0 |
到循环结束需要迭代的次数(从 0 开始) |
loop.first |
如果是第一次迭代,为 True 。 |
loop.last |
如果是最后一次迭代,为 True 。 |
loop.length |
序列中的项目数。 |
loop.cycle |
在一串序列间期取值的辅助函数。见下面示例程序。 |
| {% for post in posts%} |
| {{loop.index}}, {{post.title}} |
| {% endfor %} |
| 1, Post title |
| 2, Second Post |
- cycle函数会在每次循环的时候,返回其参数中的下一个元素,可以拿上面的例子来说明:
| {% for post in posts%} |
| {{loop.cycle('odd','even')}} {{post.title}} |
| {% endfor %} |
| odd Post Title |
| even Second Post |
示例程序
- 实现的效果
![]()
| |
| my_list = [ |
| { |
| "id": 1, |
| "value": "我爱工作" |
| }, |
| { |
| "id": 2, |
| "value": "工作使人快乐" |
| }, |
| { |
| "id": 3, |
| "value": "沉迷于工作无法自拔" |
| }, |
| { |
| "id": 4, |
| "value": "日渐消瘦" |
| }, |
| { |
| "id": 5, |
| "value": "以梦为马,越骑越傻" |
| } |
| ] |
| {% for item in my_list if item.id != 5 %} |
| {% if loop.index == 1 %} |
| <li style="{{ item.value }}</li> |
| {% elif loop.index == 2 %} |
| <li style="{{ item.value }}</li> |
| {% elif loop.index == 3 %} |
| <li style="{{ item.value }}</li> |
| {% else %} |
| <li style="{{ item.value }}</li> |
| {% endif %} |
| {% endfor %} |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?