diff --git a/app_web.py b/app_web.py index 2233aee..9e8667c 100644 --- a/app_web.py +++ b/app_web.py @@ -90,8 +90,12 @@ app.add_middleware( same_site="lax", ) templates = Jinja2Templates(directory=str(TEMPLATES_DIR)) -templates.env.globals["app_url"] = with_url_prefix -templates.env.globals["url_prefix"] = web_url_prefix + + +@app.middleware("http") +async def _inject_web_url_prefix(request: Request, call_next): + request.state.web_url_prefix = web_url_prefix() + return await call_next(request) @app.get("/favicon.ico", include_in_schema=False) @@ -124,8 +128,6 @@ def template_response(request: Request, name: str, context: Dict[str, Any]): _template_response_new_style = bool(keys) and keys[0] == "request" ctx = dict(context) ctx.setdefault("request", request) - ctx["app_url"] = with_url_prefix - ctx["url_prefix"] = web_url_prefix() if _template_response_new_style: return templates.TemplateResponse(request, name, ctx) return templates.TemplateResponse(name, ctx) diff --git a/templates/index.html b/templates/index.html index 675f7fb..e6595b4 100644 --- a/templates/index.html +++ b/templates/index.html @@ -1,3 +1,12 @@ +{# app_url:Jinja 宏,不依赖 Python 往 context 注入;前缀来自中间件 request.state.web_url_prefix(WEB_URL_PREFIX)或 ASGI root_path #} +{% macro app_url(path) -%} +{%- set _p = path if path.startswith('/') else '/' ~ path -%} +{%- set pre = (request.state.web_url_prefix | default('', true)) | trim -%} +{%- if not pre -%} +{%- set pre = request.scope.get('root_path', '') | trim -%} +{%- endif -%} +{{- pre ~ _p if pre else _p -}} +{%- endmacro %}
@@ -1038,7 +1047,7 @@