【问题标题】:Django template variable value to string literal comparison failsDjango 模板变量值与字符串文字比较失败
【发布时间】:2011-04-13 12:35:48
【问题描述】:

我的模板中有以下代码应该将watchinstance.shift 的值(可以是“DAY”或“NIGHT”)与文字字符串“DAY”进行比较。比较总是失败。

{% for watchinstance in watchinstance_list %}
    {% if watchinstance.shift == "DAY" %}
        <p>shift is DAY</p>
    {% endif %}
{% endfor %}

使用ifequal 也不起作用:

{% for watchinstance in watchinstance_list %}
    {% ifequal watchinstance.shift "DAY" %}
        <p>shift is DAY</p>
    {% endifequal %}
{% endfor %}

但是,只需调用 {{ watchinstance.shift }} 即可按预期工作:

{% for watchinstance in watchinstance_list %}
    {{ watchinstance.shift }}
{% endfor %}

返回 DAY 和 NIGHT。

我检查了watchinstance.shift 是否返回任何额外的字符,但它看起来不像......我还能在这里遗漏什么?

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    几种可能性:

    1. .shift 字符串有额外的空格。使用它来仔细检查:

      {% for watchinstance in watchinstance_list %}
          X{{ watchinstance.shift }}X
      {% endfor %}
      
    2. .shift 属性不是字符串,而是字符串化为“DAY”或“NIGHT”的对象。在这种情况下,{{ watchinstance.shift }} 中的变量替换看起来与字符串相同,但 {% ifequal watchinstance.shift "DAY" %} 中的比较会失败。

    【讨论】:

    • 1) 是的,这就是我最初检查额外字符的方式。没有。
    • 2) 我怀疑这与它有关!它确实是移位模型实例的外键引用!找了2个小时终于找到了一种把它串起来的方法!
    【解决方案2】:

    所以在搜索Django docs 2小时后,我终于找到了让它工作的方法:

    {% if watchinstance.shift|stringformat:"s" == "DAY"  %}
    

    【讨论】:

    • 在我的情况下,我正在使用上述方法并运行“无法解析剩余部分:'=='IP'' from 'item.status=='IP'' 的问题。问题原来是“==”前后缺少空格。如果“==”前后没有空格,它将不起作用。希望对某人有所帮助。
    猜你喜欢
    • 2012-06-06
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 2013-11-27
    • 1970-01-01
    • 2012-06-04
    相关资源
    最近更新 更多