views:

110

answers:

3

I'm using Django's render_to_response to write data out to an html page, but I'd also like that render_ to _response call to load a python dictionary into a javascript associative array. What's the best way to do this?

A: 

What does that mean exactly? If you mean you think data in the template is in JavaScript terms, it isn't: You can use python objects in the template directly. If you mean, how do I embed a JSON literal from a Python dictionary or list into my template: Encode it with simplejson, which is included with Django.

But, you often don't want to do this for a couple reasons. If you include this dynamic data in the template, you can't cache it as easily. Shouldn't this be another view that is generating a JS file you're including? Or maybe an AJAX call to grab the data once the page is live? Take the pick for what best fits you situation.

ironfroggy
+3  A: 

Convert it to JSON and include, in your template.html, inside a <script> tag, something like

var my_associative_array = {{ json_data }}

after having JSON-encoded your Python dict into a string and put it in the context using key json_data.

Vinay Sajip
+1  A: 

Vinay Sajip is close however you add to add the safe filter to avoid django from auto escaping the json data, so this would work (there are other ways to stop the auto escaping but this is the easiest one):

 var my_associative_array = {{ json_data|safe }}
googletorp