How to process an array of django templates and use it in javascript?

So here is the problem, I have an html template that looks something like this:

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

from the server I pass the list to this element, 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 can I pass it javascript ...?

+4
source share
2 answers

you should have an identifier in your html with the displayed variable and look at it there, let's make an example:

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

and in your javascript:

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

It is assumed that you are using jQuery.

I really don't know why this template assigned a variable, but you should not provide any information about javascript code, since there is a moment when you are going to take this js and put it in a compressed file, or move it, or reuse it it will be very difficult to do if you provided the values โ€‹โ€‹of the variables in this way.

hope this helps!

0
source

The problem is that the string representation of the array is not valid JavaScript. u' at the beginning is not good. It:

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

should be as follows:

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

You have two options. In the view function, encode it as JSON there:

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

or create a filter that you can use. See this for an example. Then use is simple:

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

All Articles