12

Say I have settings.py file with a bunch of constants (maybe more, in the future). How do I access those variables in a Jinja template?

1

2 Answers 2

19

Flask automatically includes your application's config in the standard context. So if you used app.config.from_envvar or app.config.from_pyfile to pull in the values from your settings file, you already have access to those values in your Jinja templates (e.g., {{ config.someconst }}).

1
  • i'm not able to do this, maybe its outdated for 2023, restarted my serve, tried everything already
    – greendino
    Commented Apr 5, 2023 at 4:46
7

You need to define a context_processor:

@app.context_processor
def inject_globals():
    return dict(
        const1 = const1,
        const2 = const2,
    )

Values injected this way will be directly available in templates:

<p>The values of const1 is {{ const1 }}.</p>

You'll probably want to use the Python dir function to avoid listing all of the constants.

4
  • Thanks. So can I access them in all the templates automatically? (e.g. {{ g.const1 }})
    – john2x
    Commented Aug 11, 2011 at 12:22
  • @john2x: The constants will be available directly, see my updated answer. But I think ddbeck's answer may better suit your needs.
    – Helgi
    Commented Aug 11, 2011 at 19:50
  • Thanks. I guess app.config is the "standard" way?
    – john2x
    Commented Aug 12, 2011 at 21:33
  • they are not available in macros. why?? Commented Oct 13, 2014 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.