69

I am using Flask version 0.7. I have stored the path of static content in a configuration file and loaded it using

app.config.from_envvar(<file_name>)

Can I be able to access this config variable in the template without passing the variables through the view?

Dot NET
  • 4,891
  • 13
  • 55
  • 98
ranendra
  • 2,492
  • 2
  • 19
  • 29
  • I used app.config.from_pyfile() to load the configuration to flask config variable. Since Flask 0.6; config, being one of the global variable, is available in Jinja2 templates by default. Then the config variables can be easily accessed as a dictionary object in the templates. – ranendra Aug 18 '11 at 12:14

1 Answers1

129

There are a few global variables that are passed in the templates context by default by flask (here is the complete list), one of them being config, which allows you to access the application configuration from templates. Being a dictionary, it can be accessed using the syntax config['MY_CONFIGURATION'] or config.MY_CONFIGURATION (this syntax for accessing dict items is specific to Jinja).

On the other hand, if you wanted to pass arbitrary data to your templates without having to pass it explicitely in each view, you would have to use context processors.

mdeous
  • 17,513
  • 7
  • 56
  • 60
  • 24
    I'd just like to note that "Only values in uppercase are actually stored in the config object"; this gave me a few minutes of confusion when faced with the same question as the poster. – mikewaters Mar 21 '12 at 17:00
  • 3
    Don't forget to reload Flask if you are storing your config values in a Python file in debug mode, changes in this file are not watched. – Epoc Jun 16 '16 at 09:31
  • 8
    Example usage in template: `{{ config.MY_CONFIGURATION }}` – Mesut Tasci Oct 07 '16 at 12:44
  • This simple solution works fine. To check how this solution integrates with Docker, one could check out this [post](http://docker.lhsm.com.br/6641cdd6-346f-4f17-be6d-4ae954010d92). –  Jan 04 '19 at 12:30
  • doesn't work anymore, any update? – greendino Apr 05 '23 at 04:47