Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling an undefined template variable in Tornado

Tags:

python

tornado

This is a tornado template (say, in the file logout.html) I render on an error in the logout process:

  {% if logout_error %}
    Oops! The logout failed. Please close all open documents and try again
  {% end %}

This can be called using

self.render("logout.html", logout_error=True)

If the logout is successful, I have to do

self.render("logout.html", logout_error=False)

If I ignore logout_error=False, I get

NameError: global name 'logout_error' is not defined

If there are a lot of flags (which are false), the keyword arguments can pile up. Is there a way I can ask the template to consider logout_error as False if it does not exist?

like image 406
Elvis D'Souza Avatar asked Apr 13 '12 10:04

Elvis D'Souza


3 Answers

Hacking around using locals().get() is one way to do it. Another, bit more orthodox is using try. Tornado template supports it, so you can:

{% try %}
  {% if logout_error %}
    Oops! The logout failed. Please close all open documents and try again
  {% end %}
{% except %}
{% end %}
like image 136
vartec Avatar answered Nov 05 '22 04:11

vartec


You can use

{% if locals().get('logout_error', False) %}

Substitute False with the value you want if the property is not set.

like image 15
phihag Avatar answered Nov 05 '22 03:11

phihag


{% if locals().get('logout_error', False) %} not works because variables not passed as in **kwargs;

{% if globals().has_key('logout_error') %} works to me because my variables are passed separately, https://groups.google.com/forum/#!topic/python-tornado/dyl50NO3yzE this page has more disscussion on this problem.

like image 1
shenyan Avatar answered Nov 05 '22 04:11

shenyan