Syed Jafer
Syed Jafer

Reputation: 306

How to iterate the values in the list in django template?

I am going to print four array values simultaneously in django template . like this the four arrays are of equal length ,they are header_list , domain_list , domain_data , dom

for i in range(10):
      print headerlist[i]
      print domain_list[i]
      print domain_data[i]
      print dom[i]

how to acheive these in django template .

also tried

from django import template

register = template.Library()
@register.filter(name='myrange')
def myrange(number):
    return range(number)

Upvotes: 0

Views: 3237

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599778

You should zip these items in the view, rather than sending them separately to the template.

data = zip(header_list , domain_list , domain_data , dom)
return render(request, 'my_template.html', {'data': data, ...})

Now you can do:

{% for item in data %}
    Header: {{ item.0 }}
    Domain: {{ item.1 }}
    Domain data: {{ item.2 }}
    Dom: {{ item.3 }}
{% endfor %}

Upvotes: 1

Astik Anand
Astik Anand

Reputation: 13057

It can be done this way:

views.py

n = len(headerlist)
context['n'] = range(n)

Now in template

{% for i in n %}
   {{headerlist.i}}
   {{domain_list.i}}
   {{domain_data.i}}
   {{dom.i}}
{% endfor %}

Upvotes: 0

Related Questions