Reputation: 1432
I have a Flask app I'm building and I'm having issues accessing my jinja2 globals variables from within my templates, any idea as to what I'm doing wrong here?
__init__.py
from config import *
...
#Initialize Flask App
app = Flask(__name__)
#Jinja2 global variables
jinja_environ = app.create_jinja_environment()
jinja_environ.globals['DANISH_LOGO_FILE'] = DANISH_LOGO_FILE
jinja_environ.globals['TEMPLATE_MEDIA_FOLDER'] = TEMPLATE_MEDIA_FOLDER
...
config.py
...
TEMPLATE_MEDIA_FOLDER = '../static/img/media_library/' #This is the location of the media_library relative to the templates directory
DANISH_LOGO_FILE = '100danish_logo.png'
...
example template
<p>{{ TEMPLATE_MEDIA_FOLDER }}</p>
In this instance, TEMPLATE_MEDIA_FOLDER prints out nothing to the template.
Upvotes: 3
Views: 12211
Reputation: 438
The accepted answer works, but it gave me the pylint error
[pylint] E1101:Method 'jinja_env' has no 'globals' member
Do it this way to avoid the error:
app = Flask(__name__)
app.add_template_global(name='DANISH_LOGO_FILE', f=DANISH_LOGO_FILE)
Upvotes: 5
Reputation: 26427
I'm going to assume you are using Flask's render_template
function here which is by default linked to the application's jinja_env
attribute.
So try something like this,
app = Flask(__name__)
app.jinja_env.globals['DANISH_LOGO_FILE'] = DANISH_LOGO_FILE
app.jinja_env.globals['TEMPLATE_MEDIA_FOLDER'] = TEMPLATE_MEDIA_FOLDER
Upvotes: 13