On 28/02/17 15:24, Marten Kenbeek wrote:
What about adding a filter |definedthat returns True if a variable is defined, False otherwise? It may not solve any problems when it's left implicit, but at least it allows users the explicitly define the behaviour for non-existing template variables, and it makes the intention of the template code crystal clear. And of course it's fully backwards compatible. The drawback is perhaps the resulting verbosity of if statements:

{% if user.role|defined and roles.staff|defined and user.role == roles.staff %}
        [sensitive information here]
    {% endif %}


The only way to do it would be to hard code this filter into the template engine, because otherwise the 'defined' filter runs too late to know whether the variable is defined. This is really hacky and magic.

The alternative would be for this filter to take a string e.g.:


{% if "user.role"|defined and "roles.staff"|defined and user.role == roles.staff %}
        [sensitive information here]
    {% endif %}

As an analogy, in Python you can't write:

    if hasattr(foo.bar)

you have to write:

    if hasattr(foo, 'bar')

Another alternative would be to have some special syntax that could check for defined variables e.g.

   {% if user.role? and roles.staff? and user.role == roles.staff %}

My own preference, if I had a time machine, would be to have missing data/attributes just raise NameError/KeyError/AttributeError, and then have special syntax for replacing missing values with None - like https://msdn.microsoft.com/en-us/library/dn986595(v=vs.140).aspx .

However, I think that any option involving special syntax here has already got way too complex for the design philosophy of Django templates - to be simpler than normal Python code, and more designer friendly - this would take us in the opposite direction.

Luke

--
You received this message because you are subscribed to the Google Groups "Django 
developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/c1bada04-9852-e49a-e651-b12c68dcb284%40cantab.net.
For more options, visit https://groups.google.com/d/optout.

Reply via email to