代码之家  ›  专栏  ›  技术社区  ›  Evg

Django模板:假与无

  •  14
  • Evg  · 技术社区  · 16 年前

    我怎么区分 None False 在Django模板中?

    {% if x %}
    True 
    {% else %}
    None and False - how can I split this case?
    {% endif %}
    
    5 回复  |  直到 10 年前
        1
  •  12
  •   Alasdair    10 年前

    每个django template context contains true , false and none 。对于django 1.10及更高版本,可以执行以下操作:

    %if x%
    真
    %elif x是none%
    没有
    {%/%%}
    假(或空字符串、空列表等)
    {%Endif%}
    < /代码> 
    
    

    Django 1.9及更早版本不支持isoperator in theiftag.大多数情况下,可以使用%if x==none%.

    %if x%
    真
    %elif x==none%
    没有
    {%/%%}
    假(或空字符串、空列表等)
    {%Endif%}
    < /代码> 
    
    

    在视图中:

    x=true
    Y =假
    Z=无
    < /代码> 
    
    

    在模板中:

    x yesno:“true,false,none”
    是否:“真、假、无”
    Z是:“真、假、无”
    < /代码> 
    
    结果:

    <预> <代码>真 假 没有人 < /代码>
    None
    . 对于django 1.10及更高版本,可以执行以下操作:

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

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

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

    使用django 1.4及更早版本,您无法访问,没有在模板上下文中,可以使用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
    

    对于django 1.4及更早版本,您没有权限访问模板上下文中的true>,falseandnone,您可以使用yesnofilter instead.

        2
  •  5
  •   Ned Batchelder    16 年前

    可以创建自定义筛选器:

    @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 %}
    

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

        3
  •  2
  •   augustomen    14 年前

    先前答案的增强可能是:

    {% 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 %}
    
        4
  •  0
  •   Pedro Romano    13 年前

    创建上下文处理器(或从 django-misc 模块 misc.context_processors.useful_constants True , False , None 常量和用途 {% if x == None %} {% if x == False %}

    context_processor.py :

    def useful_constants(request):
        return {'True': True, 'False': False, 'None': None}
    
        5
  •  0
  •   Don    13 年前

    另一个棘手的方法是:

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

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