Django模板通过forloop.counter访问列表项 [英] django template access to list item by forloop.counter

查看:92
本文介绍了Django模板通过forloop.counter访问列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历Django模板中模型的查询集.我可以简单地使用Django for循环来做到这一点,但是超过1个步骤就无法做到,这是我的代码

I want to loop over my model's query set in the Django template. I can do it simply using Django for loop but I can not do it for steps more than 1,Here is my code

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

In fact I want a way to acces Map[forloop.counter+1] in my template but I have no idea how to do that

推荐答案

按照此处

Create a custom template filter as defined here 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

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

Inside your template, use it like:

{% 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.py views.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

Where to write template tags? Create a directory templatetags at the same level as models.py, views.py. Then add __init__.py and a file maps_tags.py. Write the custom tag definition in maps_tags.py. In your template, load the template tags by writing {% load maps_tags %} at the top. More documentation at https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#code-layout

这篇关于Django模板通过forloop.counter访问列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆