Skip to content

Commit 84216ef

Browse files
committed
[1.0.X] Fixed #8966 -- Changed is_safe for length_is filter to False, since its return value is a boolean, not a string.
Thanks Thomas Steinacher, carljm, and SmileyChris. Backport of r9291 from trunk. git-svn-id: http://code.djangoproject.com/svn/django/branches/releases/1.0.X@9292 bcc190cf-cafb-0310-a4f2-bffc1f526a37
1 parent a8a07c2 commit 84216ef

File tree

3 files changed

+11
-1
lines changed

3 files changed

+11
-1
lines changed

django/template/defaultfilters.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,7 @@ def length(value):
476476
def length_is(value, arg):
477477
"""Returns a boolean of whether the value's length is the argument."""
478478
return len(value) == int(arg)
479-
length_is.is_safe = True
479+
length_is.is_safe = False
480480

481481
def random(value):
482482
"""Returns a random item from the list."""

docs/howto/custom-template-tags.txt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,12 @@ Template filter code falls into one of two situations:
241241
this tricky, but keep an eye out for any problems like that when
242242
reviewing your code.
243243

244+
Marking a filter ``is_safe`` will coerce the filter's return value to
245+
a string. If your filter should return a boolean or other non-string
246+
value, marking it ``is_safe`` will probably have unintended
247+
consequences (such as converting a boolean False to the string
248+
'False').
249+
244250
2. Alternatively, your filter code can manually take care of any necessary
245251
escaping. This is necessary when you're introducing new HTML markup into
246252
the result. You want to mark the output as safe from further

tests/regressiontests/templates/filters.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,5 +277,9 @@ def get_filter_tests():
277277

278278
'escapejs01': (r'{{ a|escapejs }}', {'a': 'testing\r\njavascript \'string" <b>escaping</b>'}, 'testing\\x0D\\x0Ajavascript \\x27string\\x22 \\x3Cb\\x3Eescaping\\x3C/b\\x3E'),
279279
'escapejs02': (r'{% autoescape off %}{{ a|escapejs }}{% endautoescape %}', {'a': 'testing\r\njavascript \'string" <b>escaping</b>'}, 'testing\\x0D\\x0Ajavascript \\x27string\\x22 \\x3Cb\\x3Eescaping\\x3C/b\\x3E'),
280+
281+
# Boolean return value from length_is should not be coerced to a string
282+
'lengthis01': (r'{% if "X"|length_is:0 %}Length is 0{% else %}Length not 0{% endif %}', {}, 'Length not 0'),
283+
'lengthis02': (r'{% if "X"|length_is:1 %}Length is 1{% else %}Length not 1{% endif %}', {}, 'Length is 1'),
280284
}
281285

0 commit comments

Comments
 (0)