Iterating through two lists in Django templates

前端 未结 7 2230
甜味超标
甜味超标 2020-11-27 04:43

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
<         


        
相关标签:
7条回答
  • 2020-11-27 05:09

    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.

    0 讨论(0)
  • 2020-11-27 05:12

    You can make the foo objects properties of the moo objects on the server side.

    for f, b in zip(foo, bar):
        f.foosBar = b
    
    context = {
        "foo": foo
    }
    

    This is especially clean when the second list are properties of the first (which is typically the case).

    users = User.objects.all()
    for user in users:
        user.bestFriend = findBestFriendForUser(user)
    
    context = {
        "users": users
    }
    
    0 讨论(0)
  • 2020-11-27 05:14

    It's possible to do

    {% for ab in mylist %}
        {{ab.0}}
        {{ab.1}}
    {% endfor %}
    

    but you cannot make a call to zip within the for structure. You'll have to store the zipped list in another variable first, then iterate over it.

    0 讨论(0)
  • 2020-11-27 05:14

    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%}
    
    0 讨论(0)
  • 2020-11-27 05:21

    In views.py:

    foo = ['foo', 'bar']
    moo = ['moo', 'loo']
    zipped_list = zip(foo,moo)
    return render(request,"template.html",{"context":zipped_list}
    

    In template.html:

    {% for f,m in context%}
     {{f}}{{m}}
    {% endfor %}
    

    If f is a queryset returned from database then access it by {{f.required_attribute_name}}

    0 讨论(0)
  • 2020-11-27 05:25

    I built django-multiforloop to solve this problem. From the README:

    With django-multiforloop installed, rendering this template

    {% for x in x_list; y in y_list %}
      {{ x }}:{{ y }}
    {% endfor %}
    

    with this context

    context = {
        "x_list": ('one', 1, 'carrot'),
        "y_list": ('two', 2, 'orange')
    }
    

    will output

    one:two
    1:2
    carrot:orange
    
    0 讨论(0)
提交回复
热议问题