在外部 Javascript 中使用 Python Flask 传递参数 [英] Pass parameter with Python Flask in external Javascript
问题描述
我在我的网站上使用 Python Flask,并将几个参数传递给 Javascript.这是我的代码:
I use Python Flask for my website and I pass several parameters to Javascript. This is my code:
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html", param1="Hello")
<html>
<head>
</head>
<body>
<p>Hello World</p>
</body>
<script>console.log({{param1}})</script>
</html>
通过这种方式,它可以毫无问题地工作.这个例子是我自己的简化版.但是,如果我想将脚本放在外部文件上并像这样调用它:
With this way, it works without a problem. The example is a simplified of my own. But, if I want to have the script on an external file and call it like this:
<html>
<head>
</head>
<body>
<p>Hello World</p>
</body>
<script src="/static/js/myjs.js"></script>
</html>
而 myjs.js
文件是 console.log({{param1}})
,那么它不起作用.那么,有没有什么办法可以用 Python Flask 在外部 Javascript 文件中传递参数?
And the myjs.js
file is the console.log({{param1}})
, then it doesn't work. So, is there any way to pass parameters in external Javascript files with Python Flask?
推荐答案
如果你想用 Jinja 渲染一个文件,你需要在它上面调用 render_template
并传递所需的值.只是直接链接到静态文件显然不会这样做.一种解决方案是使用 Jinja 的 include
块.这要求myjs.js"位于templates/js"文件夹中,并将其包含在呈现的模板中,将所有模板上下文传递给包含的模板.
If you want to render a file with Jinja, you need to call render_template
on it and pass it the desired values. Just linking directly to a static file obviously doesn't do that. One solution is to use Jinja's include
block. This requires that 'myjs.js' is in the 'templates/js' folder, and will include it in the rendered template, passing all the templates context to the included template.
<script>{% include 'js/myjs.js' %}</script>
更好的解决方案是不需要在每个请求上都渲染 js,而是将参数从模板传递给 js 函数.
The better solution is to not require rendering the js on every request, and instead passing parameters to js functions from your template.
<script src="{{ url_for('static', filename='js/myjs.js') }}"></script>
<script>
my_func({{ my_var|tojson }});
</script>
这篇关于在外部 Javascript 中使用 Python Flask 传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!