4

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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

{{ js_value | safe }} seems more convenient
@LeonF: applying security best practices is not always 'convenient'. | safe does not apply any filtering, so any non-safe content is passed through into your template.
@LeonF: in Flask, the replacements are taken care of for you when you use the tojson filter. Outside of Flask, you can use the technique in this post to create a similar filter.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.