How to access flask config in javascript?

后端 未结 2 1156
不思量自难忘°
不思量自难忘° 2021-01-16 12:30

I need the config variables in javascript in my flask application. Currently, I access the config variables via:

@app.route(\'/api/getconfigs/\')
def get_con         


        
相关标签:
2条回答
  • 2021-01-16 12:40

    You could load the specific variable into your jinja2 globals like so:

    app.jinja_env.globals.update(VARIABLENAME=config['VARIABLENAME'])
    

    Then in an always included base-template load the variable into your javascript like so.

    <script>
         var config = {};
         config.VARIABLENAME = {{VARIABLENAME}};
    </script>
    

    Or just throw the whole config into your jinja2 env like so:

    app.jinja_env.globals.update(config=app.config)
    

    And then insert the specific Variable only if it is found in config.

    {% if config['VARIABLENAME'] %}
         <script>
             var config = {};
             config.VARIABLENAME = {{config['VARIABLENAME']}};
         </script>
    {% endif %}
    
    0 讨论(0)
  • 2021-01-16 12:41

    If you need the value as part of an API call, then yes, sending the value from an endpoint is correct. If you're rendering templates, then you can render the values in the JavaScript sent to the client.

    Flask injects its config into the template context. Within a template, config['key'] or config.key will access any value in the config. Since you're rendering it as JavaScript, use the tojson filter to render valid values.

    var debug = {{ config['DEBUG']|tojson }};
    
    0 讨论(0)
提交回复
热议问题