首页 > 解决方案 > 如何在嵌套的 for 循环中使用父循环计数器来访问 json 中的特定行,例如 django 模板(.html 文件)中的数据

问题描述

在以下代码中,内部 for 循环需要访问特定的条目行。换句话说,嵌套循环应该是 {% for entry in entries.(topic.id) %} 条目是一个类似 JSON 的数组,如下所示:

entries = [
    {'a', 'b', 'c'},
    {'d'},
    {'e', 'f', 'g', 'h', 'i'},
    {'j','k'}
    .
    .
    .
]
    {% for topic in topics %}
    <li>
        <h5>
            {{topic.id}} - {{topic}}
            <ul>
                <small>
                {% with i=topic.id %}
                
                {{i}}
                {% for entry in entries.i %}
                    <li>{{forloop.counter}} . {{entry}}</li>
                {% empty %}
                    <li>No entries available!</li>
                {% endfor %}

                {% endwith %}
                </small>
            </ul>

        </h5>
    </li>
    {% empty %}
    <li>
        <h4 style="color: tomato;">There is no available topic(s)</h4>
    </li>
    {% endfor %}

标签: arraysdjangofor-looptemplatestemplatetags

解决方案


自定义模板标签解决了我的问题。参考: https ://docs.djangoproject.com/en/3.2/howto/custom-template-tags/

from django import template
register = template.Library()

@register.filter
def topicID(List, i):
    return List[int(i)]

通过将此过滤器应用于嵌套的 for 循环,我的问题已经解决,我的代码现在如下:

    {% for topic in topics %}
    <li>
        <h5>
            {{forloop.counter}} - {{topic}}
            <ul>
                <small>
                {% for entry in entries|topicID:forloop.counter0%}
                    <li>{{forloop.counter}} . {{entry}}</li>
                {% empty %}
                    <li>No entries available!</li>
                {% endfor %}

                </small>
            </ul>

        </h5>
    </li>
    {% empty %}
    <li>
        <h4 style="color: tomato;">There is no available topic(s)</h4>
    </li>
    {% endfor %}

推荐阅读