从烧瓶传递变量到JavaScript

从烧瓶传递变量到JavaScript

本文介绍了从烧瓶传递变量到JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了类似的论坛,但没能得到任何解决方案的工作。我想从烧瓶传递变量到我的Java脚本文件。这些值然后将被用于我的JavaScript文件中的PubNub。



这是我的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'])

这是我的javascript代码(app.js)的一部分: / p>

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

如果我在Settings.html文件中使用它,但不在app.js文件中。

解决方案

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

main.py

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

app.js

  function myFunc(vars){
return vars

settings.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>


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 java script file. These values then will be used for PubNub from my javascript file.

Here is part of my Python code:

@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):

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.

解决方案

The mobiusklein answers 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.

main.py

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

app.js

function myFunc(vars) {
    return vars
}

settings.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>

这篇关于从烧瓶传递变量到JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 17:36