Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

Pass parameter with Python Flask in external 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>

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...