In Jinja2, how do you test if a variable is undefined?

后端 未结 6 1748
小蘑菇
小蘑菇 2020-12-07 11:54

Converting from Django, I\'m used to doing something like this:

{% if not var1 %} {% endif %}

and having it work if I didn\'t put var1 into

相关标签:
6条回答
  • 2020-12-07 12:13

    {% if variable is defined %} is true if the variable is None.

    Since not is None is not allowed, that means that

    {% if variable != None %}

    is really your only option.

    0 讨论(0)
  • 2020-12-07 12:15

    In the Environment setup, we had undefined = StrictUndefined, which prevented undefined values from being set to anything. This fixed it:

    from jinja2 import Undefined
    JINJA2_ENVIRONMENT_OPTIONS = { 'undefined' : Undefined }
    
    0 讨论(0)
  • 2020-12-07 12:21

    Consider using default filter if it is what you need. For example:

    {% set host = jabber.host | default(default.host) -%}
    

    or use more fallback values with "hardcoded" one at the end like:

    {% set connectTimeout = config.stackowerflow.connect.timeout | default(config.stackowerflow.timeout) | default(config.timeout) | default(42) -%}
    
    0 讨论(0)
  • 2020-12-07 12:23

    You could also define a variable in a jinja2 template like this:

    {% if step is not defined %}
    {% set step = 1 %}
    {% endif %}
    

    And then You can use it like this:

    {% if step == 1 %}
    <div class="col-xs-3 bs-wizard-step active">
    {% elif step > 1 %}
    <div class="col-xs-3 bs-wizard-step complete">
    {% else %}
    <div class="col-xs-3 bs-wizard-step disabled">
    {% endif %}
    

    Otherwise (if You wouldn't use {% set step = 1 %}) the upper code would throw:

    UndefinedError: 'step' is undefined
    
    0 讨论(0)
  • 2020-12-07 12:32

    From the Jinja2 template designer documentation:

    {% if variable is defined %}
        value of variable: {{ variable }}
    {% else %}
        variable is not defined
    {% endif %}
    
    0 讨论(0)
  • 2020-12-07 12:33

    {% if variable is defined %} works to check if something is undefined.

    You can get away with using {% if not var1 %} if you default your variables to False eg

    class MainHandler(BaseHandler):
        def get(self):
            var1 = self.request.get('var1', False)
    
    0 讨论(0)
提交回复
热议问题