作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个简单的任务:在 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/
我是一名优秀的程序员,十分优秀!