templates: add sum filter (#45394)
This commit is contained in:
parent
e08ac1f3d4
commit
4c8d63eaab
|
@ -2314,3 +2314,13 @@ def test_block_variables(pub, blocks_feature):
|
|||
|
||||
tmpl = Template('{% for foo in form_var_block|getlist:"foo" %}/{{ foo }}{% endfor %}')
|
||||
assert tmpl.render(context) == '/foo/foo2'
|
||||
|
||||
formdata.data = {
|
||||
'1': {
|
||||
'data': [{'123': '2', '234': '2'}, {'123': '7', '234': 'bla'}],
|
||||
'schema': {'123': 'string', '234': 'string'}
|
||||
},
|
||||
}
|
||||
formdata.store()
|
||||
tmpl = Template('{{ form_var_block|getlist:"foo"|sum }} {{ form_var_block|getlist:"bar"|sum }}')
|
||||
assert tmpl.render(context) == '9 2'
|
||||
|
|
|
@ -939,3 +939,16 @@ def test_adjust_to_working_day_weekend(settings):
|
|||
assert t.render({'value': '2020-06-20'}) == '2020-06-22'
|
||||
t = Template('{{ value|adjust_to_working_day_with_saturday }}')
|
||||
assert t.render({'value': '2020-06-20'}) == '2020-06-20'
|
||||
|
||||
|
||||
def test_sum():
|
||||
tmpl = Template('{{ "2 29.5 9,5 .5"|split|sum }}')
|
||||
assert tmpl.render({}) == '41.5'
|
||||
tmpl = Template('{{ list|sum }}')
|
||||
assert tmpl.render({'list': [1, 2, '3']}) == '6'
|
||||
assert tmpl.render({'list': [1, 2, 'x']}) == '3'
|
||||
assert tmpl.render({'list': [None, 2.0, 'x']}) == '2'
|
||||
assert tmpl.render({'list': []}) == '0'
|
||||
assert tmpl.render({'list': None}) == '' # list is not iterable
|
||||
assert tmpl.render({'list': '123'}) == '' # consider string as not iterable
|
||||
assert tmpl.render({}) == ''
|
||||
|
|
|
@ -437,6 +437,19 @@ def divide(term1, term2):
|
|||
return ''
|
||||
|
||||
|
||||
@register.filter(name='sum')
|
||||
def sum_(list_):
|
||||
if hasattr(list_, 'get_value'):
|
||||
list_ = list_.get_value() # unlazy
|
||||
if isinstance(list_, six.string_types):
|
||||
# do not consider string as iterable, to avoid misusage
|
||||
return ''
|
||||
try:
|
||||
return sum(parse_decimal(term) for term in list_)
|
||||
except TypeError: # list_ is not iterable
|
||||
return ''
|
||||
|
||||
|
||||
@register.filter
|
||||
def ceil(value):
|
||||
'''the smallest integer value greater than or equal to value'''
|
||||
|
|
Loading…
Reference in New Issue