【问题标题】:Django templates: False vs. NoneDjango 模板:假与无
【发布时间】:2010-07-15 19:36:17
【问题描述】:

如何区分 django 模板中的 NoneFalse

{% if x %}
True 
{% else %}
None and False - how can I split this case?
{% endif %}

【问题讨论】:

    标签: python django templates if-statement


    【解决方案1】:

    每个 Django 模板上下文 contains True, False and None。对于 Django 1.10 及更高版本,您可以执行以下操作:

    {% if x %}
    True 
    {% elif x is None %}
    None
    {% else %}
    False (or empty string, empty list etc)
    {% endif %}
    

    Django 1.9 及更早版本不支持if 标记中的is 运算符。大多数情况下,可以使用{% if x == None %} 代替。

    {% if x %}
    True 
    {% elif x == None %}
    None
    {% else %}
    False (or empty string, empty list etc)
    {% endif %}
    

    使用 Django 1.4 及更早版本,您无法在模板上下文中访问 TrueFalseNone,您可以改用 yesno 过滤器。

    在视图中:

    x = True
    y = False
    z = None
    

    在模板中:

    {{ x|yesno:"true,false,none" }}
    {{ y|yesno:"true,false,none" }}    
    {{ z|yesno:"true,false,none" }}    
    

    结果:

    true
    false
    none
    

    【讨论】:

      【解决方案2】:

      您可以创建自定义过滤器:

      @register.filter
      def is_not_None(val):
          return val is not None
      

      然后使用它:

      {% if x|is_not_None %}
          {% if x %}
              True
          {% else %}
              False
          {% endif %}
      {% else %}
          None
      {% endif %}
      

      当然,你也可以调整过滤器来测试你喜欢的任何条件......

      【讨论】:

      • 这是正确的答案,但你不应该这样做——它应该是 Django 内置的!
      【解决方案3】:

      对先前答案的增强可能是:

      {% if x|yesno:"2,1," %}
         # will enter here if x is True or False, but not None
      {% else %}
         # will enter only if x is None
      {% endif %}
      

      【讨论】:

      • 很好地利用了模板语言中已有的内容。
      • 我觉得这很令人困惑——你试图区分 None 和 False 一点也不明显。即使是现在我也不太明白它是如何工作的。
      • @NickPerkins,一旦你知道yesno 过滤器中的第三个参数如果x 为None,你就会得到它。
      【解决方案4】:

      使用TrueFalseNone 常量创建 context_processor(或使用 django-misc 模块 misc.context_processors.useful_constants)并使用 {% if x == None %}{% if x == False %}

      context_processor.py:

      def useful_constants(request):
          return {'True': True, 'False': False, 'None': None}
      

      【讨论】:

        【解决方案5】:

        这是另一个棘手的方法:

        {% if not x.denominator %}
            None
        {% else %}
            {% if x %}
                True
            {% else %}
                False
            {% endif %}
        {% endif %}
        

        那是因为“无”没有属性“分母”,而“真”和“假”都是1。

        【讨论】:

          猜你喜欢
          • 2011-05-12
          • 2015-03-30
          • 1970-01-01
          • 2015-04-17
          • 2017-06-14
          • 2011-04-30
          • 2012-12-11
          • 1970-01-01
          • 2017-07-16
          相关资源
          最近更新 更多