add group templatetag (for regroup objects) (#17285)
This commit is contained in:
parent
df88df87a4
commit
06f3a8690e
|
@ -164,3 +164,11 @@ def get(obj, key):
|
|||
return obj.get(key)
|
||||
except AttributeError:
|
||||
return None
|
||||
|
||||
@register.filter(name='get_group')
|
||||
def get_group(group_list, group_name):
|
||||
ret = []
|
||||
for group in group_list:
|
||||
if group['grouper'] == group_name:
|
||||
ret.extend(group['list'])
|
||||
return ret
|
||||
|
|
|
@ -75,3 +75,15 @@ def test_get():
|
|||
t = Template('{% load combo %}{{ foo|get:key }}')
|
||||
context = Context({'foo': {'foo-bar': 'hello'}, 'key': 'foo-bar'})
|
||||
assert t.render(context) == 'hello'
|
||||
|
||||
def test_get_group():
|
||||
context = Context({'cities': [
|
||||
{'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
|
||||
{'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
|
||||
{'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
|
||||
{'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
|
||||
{'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
|
||||
]})
|
||||
t = Template('{% load combo %}{% regroup cities by country as country_list %}'
|
||||
'{% for c in country_list|get_group:"USA" %}{{c.name}},{% endfor %}')
|
||||
assert t.render(context) == 'New York,Chicago,'
|
||||
|
|
Loading…
Reference in New Issue