Damir
Damir

Reputation: 56199

How to pass dictionary from Jinja2 (using Python) to Javascript?

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.

Upvotes: 4

Views: 8933

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121784

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.

Upvotes: 4

kazagistar
kazagistar

Reputation: 1597

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

Upvotes: 1

Related Questions