无法使用django变量和javascript变量进行条件转换 [英] can't make if condition with django variable and javascript variable

查看:80
本文介绍了无法使用django变量和javascript变量进行条件转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i variable type table in javascript , and i need to make a test with if condition between this variable and a variable from django database but it' doesn't work.

示例:

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

        {% if v.date ==  test_date %}

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

        {% endif %}

    {% endfor%}
        ]

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

the first example doesn't work and i don't know why.

其他示例:

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

当我将变量的值放入测试有效时

when i put the value of the variable in the test it's working

推荐答案

模板的Django部分( {%%} )在以下位置执行当在客户端(仅在浏览器中)执行javascript部分时,服务器。模板标签中的所有变量都是Django的变量。关键是django可以看到文本和模板标签。

Django part of the template( {% %}) is executed on the server, when javascript part is executed on the client side (just in the browser). All the variables inside template tags are django's variables. The point is that django sees text and template tags. It won't execute any line of jacascript.

让我展示一下django以及javascript如何看到您的第一个示例。

let me show how django and how javascript sees your first example.

django:

some text
    {% for v in vs %}

        {% if v.date ==  test_date %}

            another text

        {% endif %}

    {% endfor%}
        more text

现在您看到没有 test_date 变量。如果没有 test_date 变量(为空),则该变量不等于 v.date

Now you see that there isn't any test_date variable. If there is no test_date variable (it's empty), then it coudn't be equal to v.date.

javascript:

javascript:

var test_date = "2017-06-23";
var locations = [
        ]

如您所见(您可以检查它在浏览器的 dev工具中),您的服务器未为javascript生成任何文本,因此位置数组为空。

As you see (you can check it in dev tools of browser) your server didn't produce any text for javascript, so the locations array is empty.

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

If you simply want to test if v.date is equal to some string than you can create variable test_date in view corresponding to this template and add it to the context.

这篇关于无法使用django变量和javascript变量进行条件转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆