使用Jinja将数据发送到Javascript [英] Using jinja to send data to Javascript

查看:65
本文介绍了使用Jinja将数据发送到Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Python代码,其中我使用jinja将数据发送到Flask中的模板.我可以访问仅在HTML中找到的代码,但是当我尝试使用Javascript显示数据时,它不起作用. 例如,这是我的Python代码:

I have Python code, in which I'm using jinja to send data to a template in Flask. I can access the code just find in HTML, but when I try displaying the data in Javascript, it doesn't work. For example, here's my Python code:

name = "Steve"
return render_template('simple.html',data=json.dumps(name))

在我的simple.html代码中的html正文中:

And in my simple.html code, in the html body:

<script>
var name = {{ data }};
alert(name);
</script>

我的控制台中的错误为"SyntaxError:意外令牌'&'"

The error in my console says "SyntaxError: Unexpected token '&'"

我知道我以前曾经遇到过这个问题,但是我忘记了如何解决它.

I know I've seen this problem before, I'm forgetting how to solve it though.

推荐答案

没关系,我明白了.我需要使用保险箱来转义代码.示例:

Never mind, I got it. I needed to use safe to escape the code. Example:

<script>
var name = {{ data|safe }};
alert(name);
</script>

这篇关于使用Jinja将数据发送到Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆