在外部 javascript 文件中使用 Jinja2 模板引擎
我正在使用 Python 和 Flask 开发一个 Web 项目.我只是想知道我是否可以在我的外部 javascript 文件中访问由 python 发送的参数?它适用于 html 文件或嵌入在 html 文件中的 js,但不适用于 javascript 为 extern 的情况.
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.
见下文.
python代码
@app.route('/index')
def index():
return render_template('index.html', firstArg = 2, secondArg = 3)
index.html 代码
The index.html code
...
<body>
<p>The first arg is {{firstArg}}.</p>
<script src="index.js"></script>
</body>
...
还有 index.js 文件
And the index.js file
window.onload=function(){
console.log('{{secondArg}}');
};
所以第一个 arg 在 html 文件中是正确的,但第二个在 js 文件中不起作用.浏览器显示 Unexpected token {
.
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 {
.
也许不能在外部js中使用它?
Maybe it's not possible to use it in external js?
否则我需要将 secondArg 作为输入数据插入到 html 中并将其放入 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.
index.js 可能不是由您的烧瓶实例提供的,但它绝对不是由您的模板引擎处理的,即使它不会有与请求的 html 相同的上下文.
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.
我认为最干净的解决方案是在您的 index.js
中有一个启动函数并从 html 文件中调用它:
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>
你也可以告诉flask路由index.js:@yourapp.route('index.js')
就像你对route('/index')
但这可能不是一个好主意.
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.