Handling an undefined template variable in Tornado

后端 未结 4 892
Happy的楠姐
Happy的楠姐 2021-02-05 13:59

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         


        
相关标签:
4条回答
  • 2021-02-05 14:15

    You can use

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

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

    0 讨论(0)
  • 2021-02-05 14:28

    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 %}
    
    0 讨论(0)
  • 2021-02-05 14:33

    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 %}
    
    0 讨论(0)
  • 2021-02-05 14:34

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

    0 讨论(0)
提交回复
热议问题