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和Flask进行Web项目。我只是想知道我是否可以在外部javascript文件中访问python发送的参数?它适用于html文件或嵌入在html文件中的js,但是当javascript是extern时则不行。
See below.
见下文。
The python code
python代码
@app.route('/index')
def index():
return render_template('index.html', firstArg = 2, secondArg = 3)
The index.html code
index.html代码
...
<body>
<p>The first arg is {{firstArg}}.</p>
<script src="index.js"></script>
</body>
...
And the index.js file
和index.js文件
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 {
.
所以第一个arg在html文件中是正确的,但第二个在js文件中不起作用。浏览器显示意外的令牌{。
Maybe it's not possible to use it in external js?
也许它不可能在外部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.
否则我需要在html中插入secondArg作为输入数据并在js文件中获取它,但它不是很干净。
If someone can help, thanks.
如果有人可以提供帮助,谢谢。
1 个解决方案
#1
18
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:
我认为最干净的解决方案是在index.js中创建一个启动函数并从html文件中调用它:
<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.
您也可以告诉flask路由index.js:@ yourapp.route('index.js')就像你对路径('/ index')所做的那样,但这可能不是一个好主意。
#1
18
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:
我认为最干净的解决方案是在index.js中创建一个启动函数并从html文件中调用它:
<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.
您也可以告诉flask路由index.js:@ yourapp.route('index.js')就像你对路径('/ index')所做的那样,但这可能不是一个好主意。