1

I need to access a dictionary (country_stat) within javascript in a django template. I'm using google charts api that have this javascript code. The below code runs great and prints a neat map. But the values are static.

function drawRegionsMap() {
  var data = google.visualization.arrayToDataTable([
    ['Country', 'Popularity'],
    ['Germany', 2],
    ['United States', 3],
    ['Brazil', 4],
    ['Canada', 5],
    ['France', 6],
    ['RU', 7]
  ]);

Printing country_stat within content block is successful.

{% for key, value in country_stat.items %}
{{key}}, {{value}}
{% endfor %}

prints,

India, 2 Russia, 1 

But I don't know how to plug this into the javascript code.

2
  • have you considered using django to send you data as json? That way, you don't have to worry about templating you js code Commented May 12, 2012 at 10:50
  • no. there should be an easier way. Commented May 12, 2012 at 10:53

2 Answers 2

6

Either ask for the data by AJAX, or plop down literal JSON inside your JavaScript from the template - set a context variable in your view:

import simplejson as json
context['thingy_json'] = json.dumps(thingy)

Then include that variable in your template:

<script>
    var data = {{ thingy_json }};
</script>
Sign up to request clarification or add additional context in comments.

Comments

3

Actually solved it.

  var data = google.visualization.arrayToDataTable([
    ['Country', 'Popularity'],
    {% for key, value in country_stat.items %}
    ['{{key}}', {{value}}],
    {% endfor %}
  ]);

The problem was silly - i missed the single quotes around {{key}}

2 Comments

You shouldn't have to build the array in javascript just pass JSON from django to javascript.
While it may work for your specific dataset, you don't want to do this. Any single quote in the data will break your application. And antislashes will induce odd behaviors. See Amadan's answer for how to do this cleanly and with much less effort.

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.