2021-08-22 20:07:24 +02:00
|
|
|
import typing
|
|
|
|
|
2023-02-02 13:58:23 +01:00
|
|
|
from jinja2 import BaseLoader, Environment, pass_context
|
2021-08-22 20:07:24 +02:00
|
|
|
from starlette.datastructures import QueryParams
|
2021-09-16 19:42:05 +02:00
|
|
|
from starlette.requests import Request
|
2023-02-02 13:58:23 +01:00
|
|
|
from starlette.templating import Jinja2Templates as SuperJinja2Templates
|
2021-08-22 20:07:24 +02:00
|
|
|
|
|
|
|
|
2023-02-02 13:58:23 +01:00
|
|
|
class Jinja2Templates(SuperJinja2Templates):
|
|
|
|
def __init__(self, loader: BaseLoader) -> None:
|
|
|
|
super().__init__("")
|
2021-08-22 20:07:24 +02:00
|
|
|
self.env = self.get_environment(loader)
|
|
|
|
|
2023-02-02 13:58:23 +01:00
|
|
|
def get_environment(self, loader: BaseLoader) -> Environment:
|
|
|
|
@pass_context
|
2021-08-22 20:07:24 +02:00
|
|
|
def url_for(context: dict, name: str, **path_params: typing.Any) -> str:
|
2021-11-27 13:01:12 +01:00
|
|
|
request: Request = context["request"]
|
2021-09-16 19:42:05 +02:00
|
|
|
return request.app.url_path_for(name, **path_params)
|
2021-08-22 20:07:24 +02:00
|
|
|
|
|
|
|
def url_params_update(init: QueryParams, **new: typing.Any) -> QueryParams:
|
|
|
|
values = dict(init)
|
|
|
|
values.update(new)
|
|
|
|
return QueryParams(**values)
|
|
|
|
|
2023-02-02 13:58:23 +01:00
|
|
|
env = Environment(loader=loader, autoescape=True)
|
2021-08-22 20:07:24 +02:00
|
|
|
env.globals["url_for"] = url_for
|
|
|
|
env.globals["url_params_update"] = url_params_update
|
|
|
|
return env
|