admin管理员组

文章数量:1323342

How to pass dictionary from Jinja2 (using Python) to Javascript ? I have dictionary in Python and when I render template I need to use that dictionary with Javascript, I passed from Python

template = JINJA_ENVIRONMENT.get_template('sm.html')
self.response.write(template.render(values=values))

but how to store them in Javascript variable inside html page.

How to pass dictionary from Jinja2 (using Python) to Javascript ? I have dictionary in Python and when I render template I need to use that dictionary with Javascript, I passed from Python

template = JINJA_ENVIRONMENT.get_template('sm.html')
self.response.write(template.render(values=values))

but how to store them in Javascript variable inside html page.

Share Improve this question asked Nov 10, 2013 at 0:35 DamirDamir 56.3k98 gold badges251 silver badges368 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Use the json module to turn the Python data into JSON data; JSON is a subset of JavaScript * and does fine as a JavaScript literal:

import json

js_value = json.dumps(python_value)

and render the js_value in the template.

If you need the JSON data to be HTML safe too, you'll need to add some replacements:

js_value = (json.dumps(python_value)
    .replace(u'<', u'\\u003c')
    .replace(u'>', u'\\u003e')
    .replace(u'&', u'\\u0026')
    .replace(u"'", u'\\u0027'))

*JSON allows for U+2028 and U+2029 characters which JavaScript literals can't contain, but the json.dumps() function escapes all non-ASCII codepoints by default, so provided you don't disable ensure_ascii you are fine.

You want to store it as Json. This is javascript's native format, so you can pass that directly to a variable.

本文标签: How to pass dictionary from Jinja2 (using Python) to JavascriptStack Overflow