Fixed #18400 -- Modified length template filter to return 0 for unknown variables.

Thanks Florian for the bug report, luyikei for the initial code patch, and
Bouke for the code review feedback.
This commit is contained in:
Susan Tan 2013-10-14 22:15:13 -07:00 committed by Tim Graham
parent 84cafc2b35
commit 484f3edf1e
4 changed files with 11 additions and 3 deletions

View File

@ -578,7 +578,7 @@ def length(value):
try: try:
return len(value) return len(value)
except (ValueError, TypeError): except (ValueError, TypeError):
return '' return 0
@register.filter(is_safe=False) @register.filter(is_safe=False)

View File

@ -1688,6 +1688,11 @@ For example::
If ``value`` is ``['a', 'b', 'c', 'd']`` or ``"abcd"``, the output will be If ``value`` is ``['a', 'b', 'c', 'd']`` or ``"abcd"``, the output will be
``4``. ``4``.
.. versionchanged:: 1.8
The filter returns ``0`` for an undefined variable. Previously, it returned
an empty string.
.. templatefilter:: length_is .. templatefilter:: length_is
length_is length_is

View File

@ -267,6 +267,9 @@ Miscellaneous
* ``django.contrib.gis`` dropped support for GEOS 3.1 and GDAL 1.6. * ``django.contrib.gis`` dropped support for GEOS 3.1 and GDAL 1.6.
* The :tfilter:`length` template filter now returns ``0`` for an undefined
variable, rather than an empty string.
.. _deprecated-features-1.8: .. _deprecated-features-1.8:
Features deprecated in 1.8 Features deprecated in 1.8

View File

@ -322,8 +322,8 @@ def get_filter_tests():
'length04': ('{{ string|length }}', {'string': 'django'}, '6'), 'length04': ('{{ string|length }}', {'string': 'django'}, '6'),
'length05': ('{% if string|length == 6 %}Pass{% endif %}', {'string': mark_safe('django')}, 'Pass'), 'length05': ('{% if string|length == 6 %}Pass{% endif %}', {'string': mark_safe('django')}, 'Pass'),
# Invalid uses that should fail silently. # Invalid uses that should fail silently.
'length06': ('{{ int|length }}', {'int': 7}, ''), 'length06': ('{{ int|length }}', {'int': 7}, '0'),
'length07': ('{{ None|length }}', {'None': None}, ''), 'length07': ('{{ None|length }}', {'None': None}, '0'),
# length_is filter. # length_is filter.
'length_is01': ('{% if some_list|length_is:"4" %}Four{% endif %}', {'some_list': ['4', None, True, {}]}, 'Four'), 'length_is01': ('{% if some_list|length_is:"4" %}Four{% endif %}', {'some_list': ['4', None, True, {}]}, 'Four'),