Python 将变量从 Flask 传递给 JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37259740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:08:18  来源:igfitidea点击:

Passing variables from Flask to JavaScript

javascriptpythonflaskpubnub

提问by pang

I looked at similar forums but was not able to get any of the solutions to work. I am trying to pass variables from Flask to my JavaScript file. These values then will be used for PubNub from my JavaScript file.

我查看了类似的论坛,但无法获得任何解决方案。我试图将变量从 Flask 传递到我的 JavaScript 文件。然后这些值将用于我的 JavaScript 文件中的 PubNub。

Here is part of my Python code:

这是我的 Python 代码的一部分:

@app.route("/mysettings/")
def user_settings(): 
        return render_template('Settings.html',  project_name = session['project_name'] , publish_key = session['publish_key'] , subscribe_key = session['subscribe_key'] )

Here is part of my JavaScript code (app.js):

这是我的 JavaScript 代码 (app.js) 的一部分:

var settings = {
        channel: {{project_name}},
        publish_key: {{publish_key}},
        subscribe_key: {{subscribe_key}}
    };

this code works if I use it in my Settings.html file but not in the app.js file.

如果我在 Settings.html 文件中使用此代码但不在 app.js 文件中使用它,则此代码有效。

回答by Mauro Baraldi

The mobiuskleinanswers is pretty good, but there is "hack" you should consider. Define your Javascript method to receive params and send data as params to your function.

mobiusklein答案是相当不错的,但有“黑客”,你应该考虑的问题。定义您的 Javascript 方法以接收参数并将数据作为参数发送到您的函数。

main.py

主文件

@app.route('/')
def hello():
    data = {'username': 'Pang', 'site': 'stackoverflow.com'}
    return render_template('settings.html', data=data)

app.js

应用程序.js

function myFunc(vars) {
    return vars
}

settings.html

设置.html

<html>
    <head>
         <script type="text/javascript" {{ url_for('static', filename='app.js')}}></script>
         <script type="text/javascript">
            myVar = myFunc({{vars|tojson}})
         </script>
    </head>
</html>

回答by shrishinde

Simple way to pass variables from flask view to template to javascript file with simple example mentioned by @mauro.

使用@mauro 提到的简单示例将变量从flask 视图传递到模板到javascript 文件的简单方法。

main.py

主文件

@app.route('/')
def hello():
    data = {'username': 'Pang', 'site': 'stackoverflow.com'}
    return render_template('settings.html', data=data)

settings.html

设置.html

<html>
    <head>
         <script type="text/javascript">
            var username = {{ data.username }}
            var site = {{ data.site }}
        </script>
        <script type="text/javascript" src="app.js"></script>
    </head>
</html>

app.js

应用程序.js

function myFunc() {
    return username + site
}

回答by mobiusklein

The reason is that jinja2needs to be used to perform the substitution, which from your code doesn't appear to be happening.

原因是jinja2需要使用它来执行替​​换,这从您的代码中似乎没有发生。

Chances are you're serving app.jsas a static file, which means that it is never looked at by the templating engine machinery, just served as is.

app.js很有可能作为静态文件提供服务,这意味着模板引擎机制永远不会查看它,只是按原样提供服务。

You can accomplish what you're describing by serving app.jsfrom a URL which is tied to an action which passes the contents of app.jsthrough Flask's render_templatefunction, performing jinja2substitutions, and all the other customization information, but that means jinja2has to parse the whole file, which can be expensive.

您可以通过app.js从绑定到app.js通过 Flaskrender_template函数传递内容、执行jinja2替换和所有其他自定义信息的操作的 URL提供服务来完成您所描述的内容,但这意味着jinja2必须解析整个文件,这可以贵。

You might try to pass those variables along using an AJAX request responded to by an action that sends back that same data in JSON. This is a much more common practice, and has the added value of making that data visible to other resources.

您可能会尝试使用 AJAX 请求来传递这些变量,该请求由以 JSON 形式发回相同数据的操作响应。这是一种更常见的做法,并且具有使该数据对其他资源可见的附加价值。

回答by joash

<script type="text/javascript">
   var username ='{{ data.username }}'
   var site ='{{ data.site}}'
<script>