【问题标题】:How to compare a var with an integer (0) in Django Template?如何在 Django 模板中将 var 与整数 (0) 进行比较?
【发布时间】:2017-05-20 18:19:06
【问题描述】:

我无法弄清楚这一点,它快把我逼疯了!看起来很简单,但我一定错过了一些东西。我正在尝试将计数(整数)与 0 进行比较,如果计数的值为 0,则使用 noty 打印一条消息。这是我的代码:

var count = 0;
{% for inf in prospect.prospect_industries.all %}
    {% if inf.is_interested %}
        count = count + 1;
    {% endif %}
{% endfor %}

displayNotification(count + " " + zero); //I see 0 0 in the message
{% if count == 0 %}
    displayNotification("Count is 0!!!!");
{% endif %}

我错过了什么?我尝试使用 "0" |add:0 来转换 count 变量,但没有任何效果,它永远不会进入 if 检查 if count == 0。

感谢您的帮助!

【问题讨论】:

    标签: html django django-models django-templates


    【解决方案1】:

    count 是您代码中的 Javascript 变量,因此请使用 Javascript if 语句:

    if (count === 0) {
        displayNotification("Count is 0!!!!");
    }
    

    您只能将 {% if %} 与从视图传递到模板上下文的变量一起使用(或在所有模板中可用的变量,例如 user 等)。

    【讨论】:

    • 哇。我不敢相信我没有注意到这一点。我想我今天看这段代码太久了。谢谢!
    • @user2573690 哈哈,是的,我很清楚那种感觉。我们都去过那里——或者至少我去过...
    猜你喜欢
    • 2011-02-15
    • 1970-01-01
    • 2015-05-05
    • 2013-04-06
    • 2014-01-26
    • 2012-05-03
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    相关资源
    最近更新 更多