跳转至

条件控制

本页面介绍如何在模板中使用条件控制。

基本条件

if 语句

{% if condition %}
显示内容
{% endif %}

if-else 语句

{% if total > 1000 %}
大额订单
{% else %}
普通订单
{% endif %}

if-elif-else 语句

{% if score >= 90 %}
优秀
{% elif score >= 80 %}
良好
{% elif score >= 60 %}
及格
{% else %}
不及格
{% endif %}

条件表达式

比较运算符

{% if amount > 1000 %}
{% if status == "active" %}
{% if count >= 10 %}
{% if price < 100 %}

逻辑运算符

{% if is_vip and total > 1000 %}
{% if status == "active" or status == "pending" %}
{% if not is_expired %}

完整示例

示例1: 订单状态

模板:

订单编号: {{order_no}}
状态: {% if status == "paid" %}
已支付
{% elif status == "pending" %}
待支付
{% else %}
已取消
{% endif %}

数据:

from symphra_excel.templates import TemplateWorkbook

with TemplateWorkbook("order_template.xlsx") as template:
    data = {
        "order_no": "ORD-001",
        "status": "paid",
    }

    template.render(data)
    template.save("order_rendered.xlsx")

示例2: VIP 折扣

模板:

客户: {{customer_name}}
原价: {{original_price}}
折扣: {% if is_vip %}
9折优惠
{% else %}
无折扣
{% endif %}
实付: {% if is_vip %}
{{original_price * 0.9}}
{% else %}
{{original_price}}
{% endif %}

数据:

data = {
    "customer_name": "张三",
    "original_price": 1000,
    "is_vip": True,
}

条件循环结合

过滤列表

{% for item in items %}
{% if item.quantity > 0 %}
{{item.name}} - 库存: {{item.quantity}}
{% endif %}
{% endfor %}

条件样式

from symphra_excel.templates import TemplateWorkbook

with TemplateWorkbook("report_template.xlsx") as template:
    data = {
        "sales": [
            {"product": "A", "amount": 1500, "target": 1000},
            {"product": "B", "amount": 800, "target": 1000},
            {"product": "C", "amount": 1200, "target": 1000},
        ]
    }

    template.render(data)
    template.save("sales_report.xlsx")

模板:

{% for sale in sales %}
{{sale.product}} - {{sale.amount}} 
{% if sale.amount >= sale.target %}
✓ 达标
{% else %}
✗ 未达标
{% endif %}
{% endfor %}

最佳实践

✅ 推荐做法

data = {
    "status": "active",
    "is_vip": True,
    "total": 1000,
}

模板:

{% if total > 500 %}
大额订单
{% endif %}

❌ 避免的做法

data = {
    "status": None,
}

模板:

{% if status %}
{% endif %}

下一步