Skip to content

Commit

Permalink
Fixed #18400 -- Modified length template filter to return 0 for unkno…
Browse files Browse the repository at this point in the history
…wn variables.

Thanks Florian for the bug report, luyikei for the initial code patch, and
Bouke for the code review feedback.
  • Loading branch information
ArcTanSusan authored and timgraham committed Jun 5, 2014
1 parent 84cafc2 commit 484f3ed
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 3 deletions.
2 changes: 1 addition & 1 deletion django/template/defaultfilters.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,7 @@ def length(value):
try:
return len(value)
except (ValueError, TypeError):
return ''
return 0


@register.filter(is_safe=False)
Expand Down
5 changes: 5 additions & 0 deletions docs/ref/templates/builtins.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions docs/releases/1.8.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions tests/template_tests/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
Expand Down

0 comments on commit 484f3ed

Please sign in to comment.