According to the starlette sources, it seems the correct way to set up globals is simply to pass them to the constructor of fastapi.templating.Jinja2Templates
as you would do with jinja2.Environment
.
So I have the following code trying to prepare for using jinja2 templates in FastAPI, with a dummy global "myglobal" for testing:
from fastapi.templating import Jinja2Templates
templates = None
try:
templates = Jinja2Templates(directory=f"{webroot}", globals={"myglobal":"somevalue"})
except Exception as e:
logger.exception("No templates folder found, skipping...")
On application startup, the exception triggers with the following output:
No templates folder found, skipping...
Traceback (most recent call last):
File "/app/main.py", line 22, in <module>
templates = Jinja2Templates(directory=f"{webroot}", globals={"myglobal":"somevalue"})
File "/app/venv/lib/python3.7/site-packages/starlette/templating.py", line 74, in __init__
self.env = self._create_env(directory, **env_options)
File "/app/venv/lib/python3.7/site-packages/starlette/templating.py", line 89, in _create_env
env = jinja2.Environment(**env_options)
TypeError: __init__() got an unexpected keyword argument 'globals'
So my question is, what am I doing wrong here? How can I pass globals to my templates in FastAPI?