- Author:
- agusmakmun
- Posted:
- December 12, 2019
- Language:
- Python
- Version:
- Not specified
- Score:
- 0 (after 0 ratings)
Django zip longest templatetags to handle more than 3 arguments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | import itertools
@register.filter
def zip_longest(list_a, list_b, *args):
"""
function to combine the dual lists
:param `list_a` is list A.
:param `list_b` is list B.
:param `*args` is optional arguments.
as one zip_longest method (with None value), eg:
>>> list_a = [1, 2, 3]
>>> list_b = [1]
>>>
>>> list(zip_longest(list_a, list_b))
[
[1, 2, 3]
[1, None, None]
]
>>> # OR more than 2 arguments
>>> list(zip_longest(list_a, list_b, [21, 22]))
[
(1, 1, 21),
(2, None, 22),
(3, None, None)
]
"""
return itertools.zip_longest(list_a, list_b, *args)
@register.filter
def add_more_zip(zip_longest, list_c):
"""
function to add more list into zipped longest.
eg:
[
('saya', 1, 'xxx'),
(None, 3, '33333')
]
{% for a, b, c in list_a|zip_longest:list_b|add_more_zip:list_c %}
{{ a }} {{ b }} {{ c }}
{% endfor %}
"""
zipped_list = list(zip_longest)
zipped_list_out = []
tmp_length = 0
for tuple_1, value in itertools.zip_longest(zipped_list, list_c):
if tuple_1 is not None:
new_tuples = tuple_1.__add__((value,))
tmp_length = len(tuple_1)
else:
tuple_1 = (None,) * tmp_length
new_tuples = tuple_1.__add__((value,))
zipped_list_out.append(new_tuples)
return zipped_list_out
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.