Opened 2 years ago

Closed 2 years ago

Last modified 2 years ago

#34124 closed Cleanup/optimization (wontfix)

Developer experience on {% with %} template tag can be improved.

Reported by: Oscar Cortez Owned by: nobody
Component: Template system Version: 4.1
Severity: Normal Keywords: template tag
Cc: om.cortez.2010@… Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The "with" template tag just caches a complex variable under a simpler name, and from the Django Documentation we know that there's two ways to use this tag:

  • normal form
    {% with alpha=1 beta=2 %}
    {% endwith %}
    
  • verbose form
    {% with business.employees.count as total %}
    {% endwith %}
    

But recently I was reviewing some code and found this:

{% with first_post_image as post_images.first.image %}
...
{% endwith %}

As we can see the order of the parameters is wrong, I was a bit surprised that the Django template engine did not throw or raised an issue while trying to render the template, and in the same way I think the ticket #32157 is directly related to this. So I believe that we can improve the DX for this template tag and enforce the values that we want to cache, this means that we should allow only valid variable names and enforce value casting.

Change History (2)

in reply to:  description comment:1 by Mariusz Felisiak, 2 years ago

Resolution: wontfix
Status: newclosed

Thanks for the report.

So I believe that we can improve the DX for this template tag and enforce the values that we want to cache, this means that we should allow only valid variable names and enforce value casting.

Unfortunately, we cannot do this without breaking backward compatibility as not only valid identifiers are not supported, e.g.

{% with key as 123żółć %}{{ 123żółć }}|{{key}}{% endwith %}

works fine. Moreover, even dotted names, e.g. post_images.first.image, are added to the context (as context["post_images.first.image"] = "some value") so they can be accessed by custom template tags (seems unlikely but...). I don't think it's worth additional complexity.

If you don't agree, please first start a discussion on the DevelopersMailingList, where you'll reach a wider audience and see what other think, and follow the triaging guidelines with regards to wontfix tickets.

comment:2 by Adam Johnson, 2 years ago

I think using logging options for missing variable errors should also catch the problematic situation. I blogged about ways to use this: https://adamj.eu/tech/2022/03/30/how-to-make-django-error-for-undefined-template-variables/

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