使用 Jinja 渲染到 JS 会产生无效数字而不是字符串 [英] Rendering to JS with Jinja produces invalid number rather than string
问题描述
我想将一个字符串传递给模板中的某个 JavaScript.但是,该字符串在 JavaScript 运行时被解释为(无效)数字.如何将字符串传递给 JavaScript 变量?
I want to pass a string to some JavaScript in a template. However, the string is being interpreted as an (invalid) number when the JavaScript runs. How do I pass a string to a JavaScript variable?
@app.route('/loadNext')
def loadNext():
return render_template('next.html', value='1.1.1.1')
$("#loadtable").ready(
function(){
var tmp = {{ value }};
alert(tmp);
});
推荐答案
问题在于
{{ '1.1.1.1' }}
呈现为
1.1.1.1
报价不包括在内.JavaScript 尝试将其解析为数字,但不能.幸运的是,Flask 为此包含了 Jinja 过滤器.
Quotes are not included. JavaScript tries to parse this as a number and can't. Fortunately, Flask includes a Jinja filter for this.
var tmp = {{ value|tojson }};
tojson
将在字符串周围包含引号,并在数值中省略它们.Jinja 呈现的过滤值是具有正确类型的有效 JavaScript.
tojson
will include quotes around strings and omit them for numeric values. The filtered value, when rendered by Jinja, is valid JavaScript with the correct type.
这篇关于使用 Jinja 渲染到 JS 会产生无效数字而不是字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!