开发者

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

开发者 https://www.devze.com 2023-03-22 18:22 出处:网络
Ok so here is a problem, I have an html template which looks something like开发者_如何学C this:

Ok so here is a problem, I have an html template which looks something like开发者_如何学C this:

<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...?


The problem is the string representation of the array isn't valid JavaScript. The u' at the start is no good. 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:

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:

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

and in your javascript:

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

That is assuming you are using 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.

hope this helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消