Issue
The problem seems very simple, yet I can't fix it.
Look at below two examples. Both give me TemplateSyntaxError.(separately) While only one should give an error.
Why is that?
(there is no template tag called aa)
You can check this by putting one at a time into the template.
it seems Django load
template tag runs wherever it was put(except comment tag) .
{% if "4" == "3" %}
{% else %}
{% load aa %}
{% endif %}
{% if "4" == "3" %}
{% load aa %}
{% else %}
{% endif %}
Solution
Look at below two examples. Both give me TemplateSyntaxError.(separately) While only one should give an error.
Django does not look at the context for {% load … %}
template tags [Django-doc]. It will load these regardless of the path. Indeed, both these templates:
{% if True %}
{% load static %}
{% endif %}
{% static "bla" %}
and:
{% if False %}
{% load static %}
{% endif %}
{% static "bla" %}
work, even though one would expect that only the first one would succeed, since {% if False %}
fails.
So Django's template languages compiles to a tree, but an if
statement does not works as a full if-then-else block: since a {% load … %}
template tag passes, it will load the library and export the items in the remainder of the file, a bit like in C++ the #define
directive does not care if it was defined in an if(condition)
block. You could thus essentially see it as the parser that first looks for load items, and then for if
-then
-else
s.
The {% load … %}
template tags are looked for before rendering the template tag, that makes perfect sense: Django compiles a template into a syntax tree where the {% foo %}
nodes translate into FooNode
s. So it has to know when it loads the template where it can find foo, not when it renders the template, since the same template can be rendered over and over again.
Regardless, you should not load template libraries conditionally, it makes the codepaths unpredictable and prone to errors. Just load the items at the top of the template.
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.