Reputation: 11228
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.
Upvotes: 1
Views: 4953
Reputation: 198324
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>
Upvotes: 6
Reputation: 11228
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}}
Upvotes: 3