无法使用 django 变量和 javascript 变量创建 if 条件

you*_*oun 0 javascript python django django-templates

我是 javascript 中的变量类型表,我需要if在此变量和 django 数据库中的变量之间使用条件进行测试,但它不起作用。

这个例子 :

var test_date = "2017-06-23";
var locations = [
    {% for v in vs %}

        {% if v.date ==  test_date %}

            ['okok',{{ v.latitude }},{{ v.longitude}}],

        {% endif %}

    {% endfor%}
        ]
Run Code Online (Sandbox Code Playgroud)

第一个例子不起作用,我不知道为什么。

另一个例子:

var test_date = "2017-06-23";
var locations = [
    {% for v in vs %}

        {% if v.date ==  "2017-06-23" %}

            ['okok',{{ v.latitude }},{{ v.longitude}}],

        {% endif %}

    {% endfor%}
        ]
Run Code Online (Sandbox Code Playgroud)

当我将变量的值放入测试中时,它正在工作

wpe*_*rak 5

template( {% %}) 的Django 部分在服务器上执行,而javascript 部分在客户端(仅在浏览器中)执行。模板标签内的所有变量都是 django 的变量。关键是 django 可以看到文本和模板标签。它不会执行任何 jacascript 行。

让我展示一下 django 和 javascript 如何看待你的第一个例子。

姜戈:

some text
    {% for v in vs %}

        {% if v.date ==  test_date %}

            another text

        {% endif %}

    {% endfor%}
        more text
Run Code Online (Sandbox Code Playgroud)

现在你看到没有任何test_date变量。如果没有test_date变量(它是空的),那么它不能等于v.date

javascript:

var test_date = "2017-06-23";
var locations = [
        ]
Run Code Online (Sandbox Code Playgroud)

如您所见(您可以在浏览器的开发工具中查看)您的服务器没有为 javascript 生成任何文本,因此该locations数组为空。

如果您只是想测试是否v.date等于某个字符串,则可以在与此模板对应的视图中创建变量 test_date并将其添加到上下文中。