14

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?

Elvis D'Souza
  • 2,273
  • 1
  • 23
  • 31

4 Answers4

17

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 %}
vartec
  • 131,205
  • 36
  • 218
  • 244
  • 1
    vartec, Thanks for your answer. I'm going to mark phihag's answer as correct (in spite of yours being fine) due to its brevity – Elvis D'Souza Apr 14 '12 at 11:26
  • 1
    This seems like the better solution to me, especially after reading this semi-cautionary tale about locals() http://stackoverflow.com/questions/1550479/python-is-using-vars-locals-a-good-practice. (Django templates fail silently by default, don't they?) – jsh Feb 21 '13 at 22:41
  • 1
    For some reason I never got `locals().get()` to work. Your solution works fine though. Thank you! +1 – Micke Sep 28 '13 at 09:07
15

You can use

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

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

phihag
  • 278,196
  • 72
  • 453
  • 469
  • 3
    As @shenyan points out below, under some circumstances (for me, if you pass in the variables to the template with `render`) your variables end up in `globals`, not `locals`. I'm not sure if it's safe to rely upon this behavior - tiny bit more discussion here: https://groups.google.com/forum/#!topic/python-tornado/MppS69GjZk0. The try/catch answer is ugly but is more resilient. – tobek Feb 20 '15 at 20:12
1

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

shenyan
  • 408
  • 4
  • 9
0

The "Tornado way" is to not have undeclared variables. It's more zen to declare the variables explicit.

Workaround:

{% if 'grok' in globals() %}
  {{grok}}
{% end %}

{% if globals().get('grok_error', False) %}
  error message
{% end %}
The Demz
  • 7,066
  • 5
  • 39
  • 43