From 484f3edf1e79388f73dcb07e39d79d0c5029ae9e Mon Sep 17 00:00:00 2001 From: Susan Tan Date: Mon, 14 Oct 2013 22:15:13 -0700 Subject: [PATCH] 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. --- django/template/defaultfilters.py | 2 +- docs/ref/templates/builtins.txt | 5 +++++ docs/releases/1.8.txt | 3 +++ tests/template_tests/filters.py | 4 ++-- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py index bb883d0fc66..e6a0c619dca 100644 --- a/django/template/defaultfilters.py +++ b/django/template/defaultfilters.py @@ -578,7 +578,7 @@ def length(value): try: return len(value) except (ValueError, TypeError): - return '' + return 0 @register.filter(is_safe=False) diff --git a/docs/ref/templates/builtins.txt b/docs/ref/templates/builtins.txt index 9d4093e4dad..e66c5837206 100644 --- a/docs/ref/templates/builtins.txt +++ b/docs/ref/templates/builtins.txt @@ -1688,6 +1688,11 @@ For example:: If ``value`` is ``['a', 'b', 'c', 'd']`` or ``"abcd"``, the output will be ``4``. +.. versionchanged:: 1.8 + + The filter returns ``0`` for an undefined variable. Previously, it returned + an empty string. + .. templatefilter:: length_is length_is diff --git a/docs/releases/1.8.txt b/docs/releases/1.8.txt index 31f4fb2cbb2..1345e55a9a8 100644 --- a/docs/releases/1.8.txt +++ b/docs/releases/1.8.txt @@ -267,6 +267,9 @@ Miscellaneous * ``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: Features deprecated in 1.8 diff --git a/tests/template_tests/filters.py b/tests/template_tests/filters.py index e13db66e969..ad7f79d8884 100644 --- a/tests/template_tests/filters.py +++ b/tests/template_tests/filters.py @@ -322,8 +322,8 @@ def get_filter_tests(): 'length04': ('{{ string|length }}', {'string': 'django'}, '6'), 'length05': ('{% if string|length == 6 %}Pass{% endif %}', {'string': mark_safe('django')}, 'Pass'), # Invalid uses that should fail silently. - 'length06': ('{{ int|length }}', {'int': 7}, ''), - 'length07': ('{{ None|length }}', {'None': None}, ''), + 'length06': ('{{ int|length }}', {'int': 7}, '0'), + 'length07': ('{{ None|length }}', {'None': None}, '0'), # length_is filter. 'length_is01': ('{% if some_list|length_is:"4" %}Four{% endif %}', {'some_list': ['4', None, True, {}]}, 'Four'),