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

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

问题描述

我想遍历我在 Django 模板中设置的模型查询.我可以简单地使用 Django for loop 来做到这一点,但我不能为超过 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

推荐答案

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

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.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

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天全站免登陆