简体   繁体   English

将变量从 Flask 传递到 JavaScript

[英]Passing variables from Flask to JavaScript

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.我正在尝试将变量从 Flask 传递到我的 JavaScript 文件。 These values then will be used for PubNub from my JavaScript file.然后这些值将用于我的 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 文件中使用,则此代码有效。

The mobiusklein answers is pretty good, but there is "hack" you should consider. mobiusklein的答案非常好,但是您应该考虑“hack”。 Define your Javascript method to receive params and send data as params to your function.定义您的 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({{data|tojson}})
         </script>
    </head>
</html>

Simple way to pass variables from flask view to template to javascript file with simple example mentioned by @mauro.通过@mauro 提到的简单示例将变量从烧瓶视图传递到模板到 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
}
<script type="text/javascript">
   var username ='{{ data.username }}'
   var site ='{{ data.site}}'
<script>

The reason is that jinja2 needs to be used to perform the substitution, which from your code doesn't appear to be happening.原因是需要使用jinja2来执行替换,从您的代码来看,这似乎没有发生。

Chances are you're serving app.js as 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.js from a URL which is tied to an action which passes the contents of app.js through Flask's render_template function, performing jinja2 substitutions, and all the other customization information, but that means jinja2 has to parse the whole file , which can be expensive.您可以通过从 URL 提供app.js来完成您所描述的事情,该 URL 与通过 Flask 的render_template函数传递app.js内容的操作、执行jinja2替换和所有其他自定义信息相关联,但这意味着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.您可能会尝试使用 AJAX 请求来传递这些变量,该请求由以 JSON 格式发回相同数据的操作做出响应。 This is a much more common practice, and has the added value of making that data visible to other resources.这是一种更为常见的做法,并且具有使该数据对其他资源可见的附加价值。

In this instance, you don't actually need to send your data with render_template() because your data is already stored in your session.在这种情况下,您实际上不需要使用 render_template() 发送数据,因为您的数据已经存储在会话中。 Your session data is already available to a jinja2 template.您的会话数据已经可用于 jinja2 模板。 (You might not be able to import it from app.js. You might need to include all the code explicitly in 'Settings.html'.) (您可能无法从 app.js 导入它。您可能需要在“Settings.html”中明确包含所有代码。)

main.py主文件

@app.route("/mysettings/")
def user_settings(): 
    return render_template('Settings.html')

settings.html设置.html

<script type="text/javascript">
var settings = {
    channel: {{ session.project_name }},
    publish_key: {{ session.publish_key }},
    subscribe_key: {{ session.subscribe_key }}
};
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM