最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

django - accessing a python dictionary in javascript - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 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>

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}}

发布评论

评论列表(0)

  1. 暂无评论