can't make if condition with django variable and javascript variable

让人想犯罪 __ 提交于 2019-12-25 08:37:54

问题


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.

the example :

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.

other example :

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


回答1:


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.

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

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:

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

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.

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.



来源:https://stackoverflow.com/questions/44636205/cant-make-if-condition-with-django-variable-and-javascript-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!