Implement custom url_for to generating urls with ROOT_PATH prefix

This commit is contained in:
Iam54r1n4
2025-02-04 16:34:52 +00:00
parent 468f4a4abc
commit 360e6ac4ba
4 changed files with 29 additions and 8 deletions

View File

@ -1 +1 @@
from .dependency import get_templates, get_session_manager
from .dependency import get_templates, get_session_manager, url_for

View File

@ -1,4 +1,8 @@
from fastapi import Request
from fastapi.templating import Jinja2Templates
from jinja2 import pass_context
from typing import Any
from starlette.datastructures import URL
from session import SessionStorage, SessionManager
from config import CONFIGS
@ -6,6 +10,21 @@ from config import CONFIGS
__TEMPLATES = Jinja2Templates(directory='templates')
@pass_context
def url_for(context: dict[str, Any], name: str = '', **path_params: dict[str, Any]) -> URL:
'''
Custom url_for function for Jinja2 to add a prefix to the generated URL.
'''
request: Request = context["request"]
url = request.url_for(name, **path_params)
prefixed_path = f"{CONFIGS.ROOT_PATH.rstrip('/')}/{url.path.lstrip('/')}"
return url.replace(path=prefixed_path)
__TEMPLATES.env.globals['url_for'] = url_for # type: ignore
def get_templates() -> Jinja2Templates:
return __TEMPLATES