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 badges2 Answers
Reset to default 4Use 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
版权声明:本文标题:How to pass dictionary from Jinja2 (using Python) to Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742134269a2422300.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论