Home > Software engineering >  How to select another array of data by subscript in a django for loop
How to select another array of data by subscript in a django for loop

Time:08-24

I have a problem when transfering two list to a html in django. I hope that it will be

a:1

b:2

Each of two data is paired. But it does not work. There have some demo codes, showing the same error. Absolutly,it has no error log,because the {{l2s.order}} is null,and the system does not throw error.Maybe my poor English makes it confusing,If there are any where no description clearly, please point out, I'll add the appropriate information。 Thanks for your help.

# fake view
def test(request):
    l1s = ["a","b","c","d","e","f"]
    l2s = ["1","2","3","4","5","6"]
    return render(request,'fake.html',locals())

# fake html 
{% for l1 in l1s% }
    {% with order=forloop.counter0 %}
    {{l1}}-{{l2s.order}}
{% endfor %}

CodePudding user response:

You can use the built in zip method for that

views.py

def test(request):
    l1s = ["a","b","c","d","e","f"]
    l2s = ["1","2","3","4","5","6"]
    context['data'] = zip(l1s, l2s)
    return render(request,'fake.html',context)

fake.html

{% for item in data %}
{{item[0]}} : {{ item[1] }} 
{% endfor %}
  • Related