跳转至

变量和循环

本页面介绍如何在模板中使用变量和循环。

变量

简单变量

{{name}}
{{title}}
{{amount}}

嵌套对象

{{user.name}}
{{order.customer.address}}
{{product.price.amount}}

循环

基本循环

在 Excel 模板中:

{% for item in items %}
{{item.name}} - {{item.price}}
{% endfor %}

循环数据

from symphra_excel.templates import TemplateWorkbook

with TemplateWorkbook("list_template.xlsx") as template:
    data = {
        "items": [
            {"name": "产品A", "price": 100},
            {"name": "产品B", "price": 200},
            {"name": "产品C", "price": 300},
        ]
    }

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

完整示例

示例1: 产品清单

模板内容:

产品名称    单价    数量    总价
{% for product in products %}
{{product.name}}  {{product.price}}  {{product.quantity}}  {{product.total}}
{% endfor %}

渲染代码:

from symphra_excel.templates import TemplateWorkbook

with TemplateWorkbook("products_template.xlsx") as template:
    data = {
        "products": [
            {"name": "笔记本", "price": 5000, "quantity": 10, "total": 50000},
            {"name": "鼠标", "price": 50, "quantity": 100, "total": 5000},
            {"name": "键盘", "price": 200, "quantity": 50, "total": 10000},
        ]
    }

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

示例2: 嵌套循环

模板:

{% for category in categories %}
分类: {{category.name}}
  {% for product in category.products %}
  - {{product.name}}: {{product.price}}
  {% endfor %}
{% endfor %}

数据:

data = {
    "categories": [
        {
            "name": "电子产品",
            "products": [
                {"name": "手机", "price": 3000},
                {"name": "平板", "price": 2000},
            ]
        },
        {
            "name": "办公用品",
            "products": [
                {"name": "笔", "price": 5},
                {"name": "本子", "price": 10},
            ]
        }
    ]
}

循环变量

循环索引

{% for item in items %}
{{loop.index}} - {{item.name}}
{% endfor %}

循环计数

{% for item in items %}
第 {{loop.index}} 项 (共 {{loop.length}} 项)
{% endfor %}

最佳实践

✅ 推荐做法

data = {
    "items": [
        {"id": 1, "name": "项目1"},
        {"id": 2, "name": "项目2"},
    ]
}

❌ 避免的做法

data = {
    "items": range(100000)
}

下一步