diff options
author | Bryan Newbold <bnewbold@archive.org> | 2020-05-12 15:50:49 -0700 |
---|---|---|
committer | Bryan Newbold <bnewbold@archive.org> | 2020-05-12 15:50:49 -0700 |
commit | ef162e8d070f51f422e57e9cfd62beb1db47e932 (patch) | |
tree | 88d77c9d55f0e75b605b1956602f1017b26783e6 /fatcat_scholar/hacks.py | |
parent | 221fe40a0440b86773ad17db967ed4335d9e4da9 (diff) | |
download | fatcat-scholar-ef162e8d070f51f422e57e9cfd62beb1db47e932.tar.gz fatcat-scholar-ef162e8d070f51f422e57e9cfd62beb1db47e932.zip |
very hack-y i18n support in jinja2 templates
Diffstat (limited to 'fatcat_scholar/hacks.py')
-rw-r--r-- | fatcat_scholar/hacks.py | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/fatcat_scholar/hacks.py b/fatcat_scholar/hacks.py new file mode 100644 index 0000000..fc1dacd --- /dev/null +++ b/fatcat_scholar/hacks.py @@ -0,0 +1,51 @@ + +import typing +import jinja2 + +from starlette.background import BackgroundTask +from starlette.templating import _TemplateResponse + +class Jinja2Templates: + """ + This is a patched version of starlette.templating.Jinja2Templates that + supports extensions (list of strings) passed to jinja2.Environment + """ + + def __init__(self, directory: str, extensions: typing.List[str] = []) -> None: + assert jinja2 is not None, "jinja2 must be installed to use Jinja2Templates" + self.env = self.get_env(directory, extensions) + + def get_env(self, directory: str, extensions: typing.List[str] = []) -> "jinja2.Environment": + @jinja2.contextfunction + def url_for(context: dict, name: str, **path_params: typing.Any) -> str: + request = context["request"] + return request.url_for(name, **path_params) + + loader = jinja2.FileSystemLoader(directory) + env = jinja2.Environment(loader=loader, extensions=extensions, autoescape=True) + env.globals["url_for"] = url_for + return env + + def get_template(self, name: str) -> "jinja2.Template": + return self.env.get_template(name) + + def TemplateResponse( + self, + name: str, + context: dict, + status_code: int = 200, + headers: dict = None, + media_type: str = None, + background: BackgroundTask = None, + ) -> _TemplateResponse: + if "request" not in context: + raise ValueError('context must include a "request" key') + template = self.get_template(name) + return _TemplateResponse( + template, + context, + status_code=status_code, + headers=headers, + media_type=media_type, + background=background, + ) |