arrays - 如何在嵌套的 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 %}
解决方案
自定义模板标签解决了我的问题。参考: 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 %}
推荐阅读
- javascript - javascript addEventListener 不起作用
- neural-network - 没有微积分的神经网络
- c++ - Qt web 引擎获取历史
- android - targetSdkVersion 26 giving exception in crash reports
- c# - Migrating ASP Web Application to .Net Core with angular 6
- plot - gnuplot - “autotitle coloumnhead”键和带有“#”的数据文件
- reflection - Kotlin 按照声明的顺序获取属性
- haskell - Haskell 中的单函数类型类命名 “呃”与“有”
- javascript - 如何在另一个对象中创建具有值的对象?
- python - Python: Runtime Error: EXIT - Program did not return 0