Flask中如何默认全局传递render_template所需数据?
Flask全局自动传入模板数据方案
方法1:用上下文处理器(最省心)
Flask自带的context_processor装饰器能帮你实现全局注入数据。注册一个函数后,它返回的字典会自动加到所有模板的上下文里,不用每个视图都手动写代码传数据。
代码示例:
from flask import Flask, render_template app = Flask(__name__) # 你的MongoDB查询函数 def fetchMappings(): # 这里写实际的数据库查询逻辑,返回目标字典 return {"nav_items": ["首页", "关于"], "site_info": {"name": "我的网站"}} # 注册上下文处理器 @app.context_processor def inject_global_mappings(): mappings = fetchMappings() # 直接返回mappings,模板里可以直接用{{ nav_items }}访问 return {'mappings': mappings} # 视图函数写法简化,不用再传mappings @app.route('/') def home(): return render_template('pages/home.html') @app.route('/about') def about(): # 要是有其他数据需要传,直接加在render_template里就行,不冲突 return render_template('pages/about.html', page_title="关于我们")
要是你习惯原来的data.mappings嵌套结构,把上下文处理器改成这样就行:
@app.context_processor def inject_global_mappings(): mappings = fetchMappings() return {'data': {'mappings': mappings}}
方法2:封装自定义渲染函数
要是不想用上下文处理器,也可以自己封装一个render_template替代Flask原生的,让它自动帮你加数据:
from flask import Flask from flask import render_template as flask_render app = Flask(__name__) def fetchMappings(): return {"nav_items": ["首页", "关于"], "site_info": {"name": "我的网站"}} # 自定义渲染函数 def render_template(template_path, **context): mappings = fetchMappings() # 处理data字段,没有就新建,有就把mappings加进去 if 'data' not in context: context['data'] = {} context['data']['mappings'] = mappings # 调用原生的render_template返回结果 return flask_render(template_path, **context) # 视图里直接用这个自定义函数 @app.route('/') def home(): return render_template('pages/home.html')
额外提醒
- 如果
fetchMappings()查询数据库比较耗时,建议给它加缓存,比如用functools.lru_cache,避免每次渲染页面都查库拖慢速度:from functools import lru_cache @lru_cache(maxsize=1) def fetchMappings(): # 数据库查询逻辑 ... - 上下文处理器返回的变量是全局的,注意别和视图函数里传的变量重名,不然会被视图里的变量覆盖。
内容的提问来源于stack exchange,提问作者Nicholas Yoannou
相关产品推荐
相关产品推荐

