4

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

2 Answers 2

8

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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!

3 Comments

ok, and how do you convert from data="[u'Afghanistan', u'Japan', u'United Arab Emirates']" to an array object in js?
you should encode the list as a json and decode it in your javascript. from django.utils import simplejson vcountries = simplejson.dumps(vcountries) and send that from your view and decode the variable with a JSON.parse on your javascript
There's no need to do this - after json encoding, it can simply be inserted as a string into the Javascript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.