You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django项目Jinja模板中如何保存外层for循环counter供内层循环使用

解决方案

问题根因

你之前的尝试不生效主要是两个语法错误:

  • {% with %}标签未添加对应的{% endwith %}闭合标签,导致变量作用域不生效
  • 父级循环属性拼写错误,正确语法为forloop.parentloop.counter,而非你尝试的forloop.parent.count

方案1:用with标签保存外层计数器(推荐,可读性更高)

{% for boards, value_dict in my_dict.items %}
    {% with outer_counter=forloop.counter %}
        {{ outer_counter }} <---- 第一层循环索引
        {% for mode, platform_dict in value_dict.items %}
            {{ outer_counter }} <---- 内层直接调用保存的变量
            {% for mode, platform_dict in value_dict.items %}
                {{ outer_counter }} <---- 深层嵌套也可直接调用
            {% endfor %}
        {% endfor %}
    {% endwith %} <---- 必须添加该闭合标签,否则变量不生效
{% endfor %}

方案2:直接调用父级循环计数器(无需额外定义变量)

{% for boards, value_dict in my_dict.items %}
    {{ forloop.counter }} <---- 第一层循环索引
    {% for mode, platform_dict in value_dict.items %}
        {{ forloop.parentloop.counter }} <---- 直接获取上一层循环计数器
        {% for mode, platform_dict in value_dict.items %}
            {{ forloop.parentloop.parentloop.counter }} <---- 多层嵌套时叠加parentloop即可
        {% endfor %}
    {% endfor %}
{% endfor %}

补充(原生Jinja2场景)

如果你使用的是原生Jinja2而非Django内置模板引擎,可直接用set语法定义变量,无需闭合标签:

{% for boards, value_dict in my_dict.items() %}
    {% set outer_counter = loop.index %}
    {% for mode, platform_dict in value_dict.items() %}
        {{ outer_counter }}
    {% endfor %}
{% endfor %}

内容的提问来源于stack exchange,提问作者user16580315

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 06:36:03