简体   繁体   English

如何:django模板传递数组并在javascript中使用它?

[英]How to: django template pass array and use it in javascript?

Ok so here is a problem, I have an html template which looks something like this: 好的,这是一个问题,我有一个html模板,看起来像这样:

<script>
    $(function() {
        var vCountries = {{ visitedCountriesList }};
    });
</script>

<..>

{{ visitedCountriesList }}

from server I pass an list to this item, but after rendering it looks like this: 从服务器我传递一个列表到这个项目,但渲染后它看起来像这样:

<script>
    $(function() {
            var vCountries = ;
        });
    </script>

    <..>

    [u'Afghanistan', u'Japan', u'United Arab Emirates']

so my question is - why ? 所以我的问题是 - 为什么? and how I can pass it to javascript...? 以及如何将其传递给javascript ...?

The problem is the string representation of the array isn't valid JavaScript. 问题是数组的字符串表示形式不是有效的JavaScript。 The u' at the start is no good. u'在开始时并不好。 This: 这个:

[u'Afghanistan', u'Japan', u'United Arab Emirates']

should be this: 应该这样:

['Afghanistan', 'Japan', 'United Arab Emirates']

You have two options. 你有两个选择。 In the view function, encode it as JSON there there: 在view函数中,将其编码为JSON:

render_to_response('my_view.html', {
    'visitedCountriesList' : json.dumps(visitedCountriesList)
})

or create a filter that you can use. 或者创建一个可以使用的过滤器。 See this one for an example. 请看这个例子。 Then usage is just: 那么用法就是:

<script>
  $(function() {
    var vCountries = {{ visitedCountriesList|jsonify }};
  });
</script>

you should have in your html an id with the variable rendered and look it there, lets do an example: 你应该在你的html中有一个带有变量渲染的id并在那里查看它,让我们做一个例子:

<...>
    <loldiv id="myvar" data="{{info}}"/>
<...>

and in your javascript: 并在您的JavaScript中:

<script>
$(function() {
    var vCountries = $("#myvar").attr("data");
});
</script>

That is assuming you are using jQuery. 假设您正在使用jQuery。

I dont really know why that template assign the variable but you should not render any information on javascript code since there is a moment where you are going to take that js and put it on a compressed file, or move it, or reuse it and it will be really hard to do it if you rendered the variable values that way. 我真的不知道为什么该模板分配变量,但你不应该渲染javascript代码的任何信息,因为有一个时刻你将把它拿到压缩文件,或移动它,或重复使用它如果你以这种方式渲染变量值,那将很难做到。

hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM