How to check if django template variable is defined

djangodjango-templates

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 %}
     ...

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.

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.

I also tried: {% ifnotequal message None %}, {% ifnotequal message '' %}, tried setting the message to None or '' explicitly, but does not seem to help.

Would appreciate some help!

Best Answer

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

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