Opened 3 years ago

Closed 2 years ago

#18742 closed Bug (duplicate)

Template tag length returns invalid value

Reported by: lukaslipka@… Owned by: nobody
Component: Template system Version: 1.4
Severity: Normal Keywords:
Cc: Triage Stage: Design decision needed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The length template tag shows some weird behavior for undefined values.

A condition such as evaluates true, when blabla is undefined:

{% if blabla|length > 5 %}
  {{ blabla|length }}
{% endif %}

Even though it evaluates true, the output of {{ blabla|length }} is 0.

Change History (3)

comment:1 Changed 3 years ago by kmtracey

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

Not sure what to do about this one. During the evaluation of the filter expression condition in the if tag, blabla is evaluated as a TemplateLiteral, which resolves the value in the context specifying ignore_failures=True:

https://github.com/django/django/blob/stable/1.4.x/django/template/defaulttags.py#L814

With ignore_failures True, the value resolves to None instead of the empty string it would resolve to if ignore_failures was False. None as the value for the length filter causes length to return an empty string:

https://github.com/django/django/blob/stable/1.4.x/django/template/defaultfilters.py#L540

Subsequently when evaluating {{ blabla|length }}, blabla is resolved with ignore_failures False, so it resolve to the empty string. And the length of the empty string is 0.

Changing TemplateLiteral eval to not specify ignore_failures=True breaks a bunch of if tag template tests. Changing the length filter to return 0 instead of the empty string for invalid inputs breaks a bunch of length filter tests. Whether either of these changes would break real code I'm not sure (length returning an empty string, in particular, seems an odd thing to me...though I can see how that may actually be used to display no output at all for non-existent data rather than 0...so I suspect changing that would in fact break things in some real code). Either of them does make the template fragment in the description behave sanely, but neither is backwards-compatible.

comment:2 Changed 2 years ago by melinath

  • Triage Stage changed from Unreviewed to Design decision needed

It sounds like this is maybe DDN.

My two cents: Changing |length to return 0 instead of an empty string makes the most sense to me. It may break some templates, true, but it wouldn't be that hard to fix.

Version 0, edited 2 years ago by melinath (next)

comment:3 Changed 2 years ago by bmispelon

  • Resolution set to duplicate
  • Status changed from new to closed

This is a duplicate of #18400.

Note: See TracTickets for help on using tickets.
Back to Top