Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

django template access to list item by forloop.counter

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 %}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 %}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...