如何使用for循环中的整数值获取django模板中的列表元素

how to use integer value from for loop to get a list element in django template

我在 views.py list=[0,1,2,3,4,5] 中有一个数字列表(我从 API) 然后在我的 search.html 我写了下面的代码:-

{% for i in list %}
    <a href="https://example.com//{{ id[i] }}">
      <img class="row_poster" src="https://this.isapi.org/{{poster[i]}}" alt="" />
      <h4>{{title[i]}}</h3>
    </a>
{% endfor %}

其中 id、poster、title 是通过 views.py

传递的列表

我想逐一获取每个列表的元素知道如何使用 它调用列表中的项目 或任何其他我可以在单个循环中访问所有列表元素的项目。

我也试过{% with abcd=i %}但结果是一样的一直报错

Could not parse the remainder: '[i]' from 'id[i]'

为此,请先创建您自己的过滤器:

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

然后您可以在模板中使用它,例如:

{% for i in list %}
    <a href="https://example.com//{{ id|get_index:i }}">
      <img class="row_poster" src="https://this.isapi.org/{{poster|get_index:i}}" alt="" />
      <h4>{{title|get_index:i}}</h3>
    </a>
{% endfor %}

有关如何注册自定义标签的信息,请查看 here