在模板中访问jinja2全局变量 [英] Access jinja2 globals variables inside template
本文介绍了在模板中访问jinja2全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在构建一个Flask应用程序,并且在从模板中访问jinja2全局变量时遇到问题,对我在这里做错什么有任何想法吗?
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'
...
示例模板
<p>{{ TEMPLATE_MEDIA_FOLDER }}</p>
在这种情况下,TEMPLATE_MEDIA_FOLDER不会在模板上打印任何内容.
In this instance, TEMPLATE_MEDIA_FOLDER prints out nothing to the template.
推荐答案
我假设您使用的是Flask的render_template
函数,默认情况下该函数链接到应用程序的jinja_env
属性.
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.
所以尝试这样的事情,
app = Flask(__name__)
app.jinja_env.globals['DANISH_LOGO_FILE'] = DANISH_LOGO_FILE
app.jinja_env.globals['TEMPLATE_MEDIA_FOLDER'] = TEMPLATE_MEDIA_FOLDER
这篇关于在模板中访问jinja2全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文