问题
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
回答1:
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
回答2:
You can combine more than one forloop and implement your custom logic for this, but not access in the same time. Below all forloops from Django 2.1 documentation.
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
tell me, What is the problem that you want solve? Maybe you can create a custom tamplate tag or template filter.
回答3:
In Django you can use {{ forloop.counter }}
index starts at 1 or {{ forloop.counter0 }}
index starts at 0.
Maybe you can use this to acces the index+1
I hope this helped. You can read more here
来源:https://stackoverflow.com/questions/53287022/django-template-access-to-list-item-by-forloop-counter