Django - How to do tuple unpacking in a template 'for' loop

后端 未结 5 950
梦毁少年i
梦毁少年i 2020-12-13 05:57

In my views.py, I\'m building a list of two-tuples, where the second item in the tuple is another list, like this:

[ Product_Type_1, [ product_1, product_2 ]         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 06:19

    it would be best if you construct your data like {note the '(' and ')' can be exchanged for '[' and ']' repectively, one being for tuples, one for lists}

    [ (Product_Type_1, ( product_1, product_2 )),
       (Product_Type_2, ( product_3, product_4 )) ]
    

    and have the template do this:

    {% for product_type, products in product_type_list %}
        {{ product_type }}
        {% for product in products %}
            {{ product }}
        {% endfor %}
    {% endfor %}
    

    the way tuples/lists are unpacked in for loops is based on the item returned by the list iterator. each iteration only one item was returned. the first time around the loop, Product_Type_1, the second your list of products...

提交回复
热议问题