admin管理员组文章数量:1326638
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.
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.
Share Improve this question asked May 12, 2012 at 10:48 John EipeJohn Eipe 11.3k24 gold badges76 silver badges119 bronze badges 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 – Jibi Abraham Commented May 12, 2012 at 10:50
- no. there should be an easier way. – John Eipe Commented May 12, 2012 at 10:53
2 Answers
Reset to default 6Either 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>
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}}
本文标签: djangoaccessing a python dictionary in javascriptStack Overflow
版权声明:本文标题:django - accessing a python dictionary in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742209376a2433422.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论