在外部JavaScript文件中使用Jinja2模板引擎 [英] Use Jinja2 template engine in external javascript file

查看:337
本文介绍了在外部JavaScript文件中使用Jinja2模板引擎的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Python和Flask开发一个Web项目。我只是想知道如果我可以在我的外部JavaScript文件中访问由python发送的参数?它可以很好地处理html文件或嵌入在html文件中的js,但是当javascript是extern的时候不会。



见下面。

python代码
$ b $ pre $ $ $ c $ @ app.route('/ index')
def index():
返回render_template('index.html',firstArg = 2,secondArg = 3)

index.html代码

  ... 
< body>
< p>第一个参数是{{firstArg}}。< / p>
< script src =index.js>< / script>
< / body>
...

和index.js文件

  window.onload = function(){
console.log('{{secondArg}}');
};

所以第一个arg在html文件中是正确的,但第二个在js文件中不起作用。浏览器显示意外的标记{



也许不能在外部js中使用它?



否则,我需要在html中插入secondArg作为输入数据,并将其在js文件中,但它不是很干净。



如果有人可以帮忙,谢谢。

解决方案

index.js可能不是由你的瓶子实例服务的,它是绝对不是由你的模板引擎处理,即使它不会有相同的上下文作为所需的HTML。

我认为最干净的解决方案将在 index.js 中有一个启动函数,并从html文件中调用它:

 <身体GT; 
< p>第一个参数是{{firstArg}}。< / p>
< script type =text / javascriptsrc =index.js>< / script>
< script type =text / javascript>
yourInitFunction({{secondArg}});
< / script>
< / body>

您也可以指示flask来路由index.js: yourapp.route('index.js')就像你用 route('/ index')做的那样,但是这可能不是一个很好主意。


I working on a web project using Python and Flask. I was just wondering if I can access parameters sent by python in my external javascript files? It's working well with html files or with js embedded in html files but not when javascript is extern.

See below.

The python code

@app.route('/index')
def index():
    return render_template('index.html', firstArg = 2, secondArg = 3)

The index.html code

...
<body>
    <p>The first arg is {{firstArg}}.</p>
    <script src="index.js"></script>
</body>
...

And the index.js file

window.onload=function(){
    console.log('{{secondArg}}');
};

So the first arg is correct within the html file but the second doesn't work in the js file. The browser is showing Unexpected token {.

Maybe it's not possible to use it in external js?

Otherwise I would need to insert the secondArg as an input data in html and get it within the js file but it's not very clean.

If someone can help, thanks.

解决方案

The index.js is probably not served by your flask instance, but it is most definitely not processed by your templateing engine and even if it would it would not have the same context as the html it is requested for.

I think the cleanest solution would be to have an initiation function in your index.js and call it from the html file:

<body>
    <p>The first arg is {{firstArg}}.</p>
    <script type="text/javascript" src="index.js"></script>
    <script type="text/javascript">
        yourInitFunction({{secondArg}});
    </script>
</body>

You also could tell flask to route the index.js, too: @yourapp.route('index.js') just like you did with the route('/index') however this is probably not a very good idea.

这篇关于在外部JavaScript文件中使用Jinja2模板引擎的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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