我有一个简单的任务:在 render_template()
函数中为不同的路由传递相同的变量。此 value
位于基本模板中,我需要将其传递给每个 render_template()
函数。我能否将此 value
设置为全局值,这样我就不必在不同路由的每个函数中都设置它?
@app.route('/hello')
def hello(name=None):
return render_template('hello.html', value=value)
@app.route('/bye')
def bye(name=None):
return render_template('bye.html', value=value)
最佳答案
要使变量可用于模板,而不必通过传递这些变量给路由增加负担,请使用 Flask 上下文处理器。参见 https://flask.palletsprojects.com/en/2.1.x/templating/#context-processors有关详细信息的示例。
这是我用来“缓存失效”CSS 的一个,这样浏览器就不会意外地使用陈旧的版本。
style_css_path = os.path.join(os.path.dirname(__file__), 'static', 'style.css')
style_css_mtime = int(os.stat(style_css_path).st_mtime)
@app.context_processor
def cache_busters():
return {
'style_css_mtime': style_css_mtime,
}
然后基本模板可以做
<link rel="stylesheet"
href="{{ url_for('static', filename='style.css') }}?v={{ style_css_mtime }}" />
任何使用 base.html 的模板都会继承此行为,而使用该模板的路由不必传递 style_css_time
。
关于python - 如何为 render_template() 创建全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72440590/