Lukas Šalkauskas
Lukas Šalkauskas

Reputation: 14361

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:

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

Upvotes: 4

Views: 5575

Answers (2)

Bialecki
Bialecki

Reputation: 31041

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>

Upvotes: 8

Hassek
Hassek

Reputation: 8995

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!

Upvotes: 1

Related Questions