FastAPI - Jinja2 控制结构


Jinja2 模板引擎提供了多种控制结构,用于控制模板的逻辑流程。以下是 Jinja2 中常用的控制结构:

1. {% if %}{% else %}

{% if %} 用于条件判断,{% else %} 用于条件不成立时的处理。

{% if user.is_authenticated %}
    Welcome, {{ user.username }}!
{% else %}
    Please log in.
{% endif %}

2. {% for %}{% endfor %}

{% for %} 用于迭代序列,{% endfor %} 用于结束循环。

<ul>
{% for item in items %}
    <li>{{ item }}</li>
{% else %}
    <li>No items found</li>
{% endfor %}
</ul>

3. {% ifchanged %}{% endifchanged %}

{% ifchanged %} 用于检查当前值是否与之前的值不同,如果不同则执行其中的代码块。

{% for item in items %}
    {% ifchanged item.category %}
        <h2>{{ item.category }}</h2>
    {% endifchanged %}
    <p>{{ item.name }}</p>
{% endfor %}

4. {% block %}{% endblock %}

{% block %}{% endblock %} 用于模板继承,允许你定义可在子模板中重写的块。

{# base.html #}
<html>
<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>

{# child.html #}
{% extends "base.html" %}
{% block content %}
    <h1>Welcome to our website!</h1>
{% endblock %}

5. {% filter %}{% endfilter %}

{% filter %} 用于应用过滤器,{% endfilter %} 用于结束过滤器的应用。

{% filter upper %}
    This text will be converted to uppercase.
{% endfilter %}

6. {% macro %}{% endmacro %}

{% macro %} 用于定义宏(类似于函数),{% endmacro %} 用于结束宏的定义。

{% macro render_post(post) %}
    <h1>{{ post.title }}</h1>
    <div>{{ post.content }}</div>
{% endmacro %}

{# 使用宏 #}
{{ render_post(post) }}

7. {% include %}

{% include %} 用于在模板中包含其他模板的内容。

{% include 'header.html' %}
    <h1>Welcome to our website!</h1>
{% include 'footer.html' %}

8. {% set %}

{% set %} 用于在模板中设置变量。

{% set navigation = ['home', 'about', 'contact'] %}

9. {% with %} 和 `{% endwith %}

{% with %} 用于设置一个临时的变量,{% endwith %} 用于结束临时的变量作用域。

{% with total=business.employees|length %}
    We have {{ total }} employees.
{% endwith %}

10. {% autoescape %}{% endautoescape %}

{% autoescape %} 用于控制自动转义行为,{% endautoescape %} 用于结束自动转义的作用域。

{% autoescape false %}
    {{ body }}
{% endautoescape %}

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

司南锤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值