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

时间:2018-11-13 18:04:25

标签: django django-templates

我想遍历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]的方法,但是我不知道该怎么做

3 个答案:

答案 0 :(得分:2)

按照此处https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#registering-custom-filters

的定义创建自定义模板过滤器
integer

在您的模板内部,像这样使用它:

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 %} templatetags相同级别上创建目录models.py。然后添加views.py和文件__init__.py。在maps_tags.py中编写自定义标签定义。在模板中,通过在顶部编写maps_tags.py来加载模板标签。有关更多文档,请访问https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#code-layout

答案 1 :(得分:2)

您可以组合多个forloop并为此实现自定义逻辑,但不能同时进行访问。下面是Django 2.1文档中的所有forloop。

forloop.counter     The current iteration of the loop (1-indexed)
forloop.counter0    The current iteration of the loop (0-indexed)
forloop.revcounter  The number of iterations from the end of the loop (1-indexed)
forloop.revcounter0     The number of iterations from the end of the loop (0-indexed)
forloop.first   True if this is the first time through the loop
forloop.last    True if this is the last time through the loop
forloop.parentloop  For nested loops, this is the loop surrounding the current one

告诉我,您要解决什么问题?也许您可以创建一个自定义模板模板或模板过滤器。

答案 2 :(得分:2)

在Django中,您可以使用{{ forloop.counter }}索引从1开始或{{ forloop.counter0 }}索引从0开始。

也许您可以使用它来获取索引+1

我希望这会有所帮助。您可以阅读更多here