gpt4 book ai didi

django 模板通过 forloop.counter 访问列表项

转载 作者:行者123 更新时间:2023-12-05 08:32:08 26 4
gpt4 key购买 nike

我想遍历 Django 模板中模型的查询集。我可以简单地使用 Django for loop 来完成,但我不能超过 1 步,这是我的代码

 {% for map in maps %}

{% if forloop.counter|divisibleby:2 %}

#Here I can access Maps with index of 1,3,5 and ..
#How can I access map with index 2,4,6 here at the same time sth like Map[forloop.counter+1]

{% endif %}


{% endfor %}

事实上,我想要一种在我的模板中访问 Map[forloop.counter+1] 的方法,但我不知道该怎么做

最佳答案

按照此处定义创建自定义模板过滤器 https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#registering-custom-filters

from django import template
register = template.Library()
@register.filter
def list_item(lst, i):
try:
return lst[i]
except:
return None

在你的模板中,像这样使用它:

{% for map in maps %}

{% if forloop.counter|divisibleby:2 %}

{% with maps|list_item:forloop.counter+1 as another_map %}

{{another_map.id}}

{% endif %}

{% endfor %}

在哪里写模板标签?models.pyviews.py同级创建目录templatetags。然后添加 __init__.py 和一个文件 maps_tags.py。在 maps_tags.py 中编写自定义标签定义。在您的模板中,通过在顶部写入 {% load maps_tags %} 来加载模板标签。更多文档在 https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#code-layout

关于django 模板通过 forloop.counter 访问列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53287022/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com