I want to do the below list iteration in django templates:
foo = ['foo', 'bar']; moo = ['moo', 'loo']; for (a, b) in zip(foo, moo): print a, b
django code:
{%for a, b in zip(foo, moo)%} {{a}} {{b}} {%endfor%}
I get the below error when I try this:
File "/base/python_lib/versions/third_party/django-0.96/django/template/defaulttags.py", line 538, in do_for raise TemplateSyntaxError, "'for' statements should have either four or five words: %s" % token.contents
How do I accomplish this?
Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.
To iterate over model instance field names and values in template with Django Python, we can use a queryset serializer. to serialize the queryset results with serializers. serialize . to loop through the data list and get the values from instance.
You can use zip
in your view:
mylist = zip(list1, list2) context = { 'mylist': mylist, } return render(request, 'template.html', context)
and in your template use
{% for item1, item2 in mylist %}
to iterate through both lists.
This should work with all version of Django.
Simply define zip as a template filter:
@register.filter(name='zip') def zip_lists(a, b): return zip(a, b)
Then, in your template:
{%for a, b in first_list|zip:second_list %} {{a}} {{b}} {%endfor%}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With