【问题标题】:Django - How to access elements in list by parent loop counter in templateDjango - 如何通过模板中的父循环计数器访问列表中的元素
【发布时间】:2017-09-10 21:22:42
【问题描述】:

我有这个代码

{% for time in listOfTimes %}
    {% for booking in someOtherList.forloop.parentloop.counter0 %}
        {{ booking }}
    {% endfor %}
{% endfor %}

booking 变量未打印。我认为这是因为我无法使用forloop 计数器访问someOtherList。我如何获得booking 值?

【问题讨论】:

  • 您想通过父循环listOfTimes 的索引值从someOtherList 访问预订?
  • 没错。
  • 你真的应该改变你的 Django 视图并构造上下文,这样逻辑就不会出现在模板之外。创建一个包含所有相关时间数据的字典列表,或者做一些事情来使循环内的循环变得微不足道。

标签: python django web django-templates


【解决方案1】:

假设你的数据如下:

listOfTimes = ['time1', 'time2']
someOtherList = [['booking1', 'booking2'], ['booking3', 'booking4']]

然后在模板中你可以这样做:

{% for time in listOfTimes %}
    {% for booking in someOtherList|get_index:forloop.counter0 %}
        {{ booking }}
    {% endfor %}
{% endfor %}

注意上面代码中的get_index过滤器,你需要在你的应用程序中编写这个自定义过滤器templatetags

from django import template

register = template.Library()

@register.filter
def get_index(l, i):
    return l[i]

注意:您的两个列表应该大小相同,否则可能会引发 IndexError

【讨论】:

    猜你喜欢
    • 2015-01-08
    • 2019-05-06
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2016-08-11
    • 2017-03-09
    相关资源
    最近更新 更多