用Jinja渲染JS会产生无效的数字而不是字符串 [英] Rendering to JS with Jinja produces invalid number rather than string

查看:132
本文介绍了用Jinja渲染JS会产生无效的数字而不是字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个字符串传递给模板中的某个JavaScript。但是,当JavaScript运行时,字符串被解释为一个(无效的)数字。如何将字符串传递给JavaScript变量?

  @ app.route('/ loadNext')
def loadNext():
return render_template('next.html',value ='1.1.1.1')


$ b $ (
函数(){
var tmp = {{value}} $($#$)$ $(#loadtable)。 ;
alert(tmp);
});


解决方案

b

  {{'1.1.1.1'}} 

呈现为

  1.1.1.1 

行情不包括在内。 JavaScript试图将其解析为一个数字,而不能。幸运的是,Flask包含一个Jinja过滤器。

  var tmp = {{value | tojson}}; 

tojson 将包含字符串引号,并省略数字值。 Jinja呈现的过滤值是正确类型的有效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);       
});

解决方案

The problem is that

{{ '1.1.1.1' }}

renders as

1.1.1.1

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 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屋!

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