is there a way to loop over two lists simultaneously in django?

前端 未结 6 1223
小鲜肉
小鲜肉 2020-12-01 16:08

I have two list objects of the same length with complementary data i want to render is there a way to render both at the same time ie.

{% for i,j in table,          


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 16:46

    If both lists are of the same length, you can return zipped_data = zip(table, total) as template context in your view, which produces a list of 2-valued tuples.

    Example:

    >>> lst1 = ['a', 'b', 'c']
    >>> lst2 = [1, 2, 3]
    >>> zip(lst1, lst2)
    [('a', 1), ('b', 2), ('c', 3)]
    

    In your template, you can then write:

    {% for i, j in zipped_data %}
        {{ i }}, {{ j }}
    {% endfor %}
    

    Also, take a look at Django's documentation about the for template tag here. It mentions all possibilities that you have for using it including nice examples.

提交回复
热议问题