如何检查django模板变量是否已定义? [英] How to check if django template variable is defined?
问题描述
我有一个django模板,可用于许多视图。该模板有一个用于消息的块,用于通知用户任何应引起注意的消息。是否发送消息取决于视图。某些视图可能会向模板发送 message
变量,而其他视图则可能不会。
I have a django template which is used from many views. The template has a block for messages used to notify user of anything that should take their attention. Whether a message is sent or not depends on the views. Some views may send a message
variable to the template while others may not.
view_1:
message = "This is an important message"
render_to_response("my_template.html",
{'message':message, 'foo':foo, 'bar':bar},
context_instance = RequestContext(request))
view_2:
message = "This is an important message"
render_to_response("my_template.html",
{'foo':foo, 'bar':bar},
context_instance = RequestContext(request))
在模板中,我检查了消息
变量并包含以下块:
In the template, I check for the message
variable and include the block as below:
base_template.html:
....
{% block main_body %}
{% block messages %}
{% endblock %}
{% block content %}
{% endblock %}
{% endblock %}
....
my_template.html:
{% extends base_template.html %}
....
{% if message %}
{% block messages %}
<div class='imp_msg'>{{ message }} </div>
{% endblock %}
{% endif %}
...
问题在于,即使view_2没有传递消息,最终的html仍使用< div class ='imp_msg'>< / div>
呈现。 -基本上是一个空的div。
Problem is that even if view_2 does not pass a message, the final html is rendered with <div class='imp_msg'></div>
-- basically an empty div.
由于CSS旨在为邮件提供浅红色背景,因此我看到的是页面顶部的空白light_red栏。
Since that CSS is designed to give a light_red background to messages, what I see is an empty light_red bar on the top of the page.
我也尝试过: {%ifnotequal message None%}
, {%ifnotequal message''%}
,尝试将消息
设置为 None
或
I also tried: {% ifnotequal message None %}
, {% ifnotequal message '' %}
, tried setting the message
to None
or ''
explicitly, but does not seem to help.
不胜感激!
推荐答案
您需要切换 {%block%}
和 {%if%}
{% block messages %}
{% if message %}<div class='imp_message'>{{ message }}</div>{% endif %}
{% endblock %}
这篇关于如何检查django模板变量是否已定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!