Opened 11 years ago
Closed 11 years ago
#22294 closed Cleanup/optimization (fixed)
length filter changes type of output to string if passed safe string
Reported by: | Owned by: | nobody | |
---|---|---|---|
Component: | Template system | Version: | dev |
Severity: | Normal | Keywords: | filter safe |
Cc: | Triage Stage: | Accepted | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | yes | UI/UX: | no |
Description
if you do:
{% if some_string|length > 123 %} Hurrah! {% endif %}
what happens is what you expect to happen - the length of the string is determined and compared to the integer given in the condition.
However if you do this:
{% if some_safe_string|length > 123 %} Booo! {% endif %}
Then the result is non obvious, since passing a safe_string to length results in the output also being marked safe and thus changed into a safe *string*... on which you cannot do simple comparisons to integers in this way... (see: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#filters-and-auto-escaping and https://github.com/django/django/blob/master/django/template/defaultfilters.py#L581 )
This seems like a bug rather than a feature, but since the type of the result of the length filter is not stated in the docs ( https://docs.djangoproject.com/en/1.5/ref/templates/builtins/#length ) this is really misleading.
Change History (2)
comment:1 by , 11 years ago
Triage Stage: | Unreviewed → Accepted |
---|---|
Type: | Uncategorized → Cleanup/optimization |
Version: | 1.5 → master |
comment:2 by , 11 years ago
Resolution: | → fixed |
---|---|
Status: | new → closed |
Hi,
I agree that this behavior is not obvious and could lead to hard-to-debug issues.
I don't really see a reason why
length
needsis_safe=True
, since it should normally return either integers, or an empty string in case of an error.In fact, making this change doesn't seem to break any existing test which is a good sign.