Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 838
Lukas Šalkauskas Avatar asked Jan 20 '23 03:01

Lukas Šalkauskas


2 Answers

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>
like image 137
Bialecki Avatar answered Jan 21 '23 16:01

Bialecki


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!

like image 45
Hassek Avatar answered Jan 21 '23 17:01

Hassek