|
17 | 17 |
|
18 | 18 | router = APIRouter() |
19 | 19 | templates = Jinja2Templates(directory="templates") |
20 | | -templates.env.globals["baidu_tongji_id"] = os.getenv("BAIDU_TONGJI_ID", "") |
21 | 20 | limiter = Limiter(key_func=get_remote_address) |
22 | 21 |
|
23 | 22 |
|
| 23 | +def _common_context() -> dict: |
| 24 | + """每次请求时动态读取的公共模板变量.""" |
| 25 | + return {"baidu_tongji_id": os.getenv("BAIDU_TONGJI_ID", "")} |
| 26 | + |
| 27 | + |
24 | 28 | @lru_cache(maxsize=128) |
25 | 29 | def load_cities() -> List[Dict]: |
26 | 30 | """加载城市数据, 如不存在则创建默认值.""" |
@@ -94,6 +98,7 @@ async def homepage(request: Request): |
94 | 98 | "schema_jsonld": schema_list, |
95 | 99 | "breadcrumbs": [], |
96 | 100 | "cities": load_cities(), |
| 101 | + **_common_context(), |
97 | 102 | }, |
98 | 103 | ) |
99 | 104 |
|
@@ -145,6 +150,7 @@ async def city_page(request: Request, city_slug: str): |
145 | 150 | ], |
146 | 151 | "city": city, |
147 | 152 | "city_content": city_content, |
| 153 | + **_common_context(), |
148 | 154 | }, |
149 | 155 | ) |
150 | 156 |
|
@@ -178,6 +184,7 @@ async def about_page(request: Request): |
178 | 184 | {"name": "首页", "url": "/"}, |
179 | 185 | {"name": "关于我们", "url": "/about"}, |
180 | 186 | ], |
| 187 | + **_common_context(), |
181 | 188 | }, |
182 | 189 | ) |
183 | 190 |
|
@@ -245,6 +252,7 @@ async def how_it_works(request: Request): |
245 | 252 | {"name": "首页", "url": "/"}, |
246 | 253 | {"name": "使用指南", "url": "/how-it-works"}, |
247 | 254 | ], |
| 255 | + **_common_context(), |
248 | 256 | }, |
249 | 257 | ) |
250 | 258 |
|
@@ -331,6 +339,7 @@ async def faq_page(request: Request): |
331 | 339 | {"name": "常见问题", "url": "/faq"}, |
332 | 340 | ], |
333 | 341 | "faqs": faqs, |
| 342 | + **_common_context(), |
334 | 343 | }, |
335 | 344 | ) |
336 | 345 |
|
|
0 commit comments