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

Maj*_*ati 1 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 %}
Run Code Online (Sandbox Code Playgroud)

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

jer*_*use 5

创建此处定义的自定义模板过滤器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
Run Code Online (Sandbox Code Playgroud)

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

{% for map in maps %}

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

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

 {{another_map.id}}

 {% endif %}

{% endfor %}
Run Code Online (Sandbox Code Playgroud)

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