How to check if django template variable is defined?

廉价感情. 提交于 2019-12-03 10:22:10

You need to switch your {% block %} and your {% if %}

{% block messages %}
    {% if message %}<div class='imp_message'>{{ message }}</div>{% endif %}
{% endblock %}
slogan621

To check, in an if statement, you need to compare the value to None, like this:

{% if some_missing_var is None %}
   // code here if some_missing_var exists
{% else %}
   // code here if some_missing_var does not exist
{% endif %}

In other cases (from the docs):

Generally, if a variable doesn’t exist, the template system inserts the value of the engine’s string_if_invalid configuration option, which is set to '' (the empty string) by default.

I tried some of the other answers, and they didn't work until I read the docs and the above was made clear.

link to docs that describe handling invalid variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!