0

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?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Mr. Developerdude
  • 9,118
  • 10
  • 57
  • 95

1 Answers1

1
from fastapi.templating import Jinja2Templates
from jinja2 import Environment

class MyTemplates(Jinja2Templates):
    def __init__(self, directory: str, globals: dict = None, **options):
        if globals is None:
            globals = {}
        jinja_env = Environment(**options)
        jinja_env.globals.update(globals)
        super().__init__(directory=directory, jinja_env=jinja_env)

You can then instantiate MyTemplates instead of Jinja2Templates and pass in your globals as a dictionary using this

templates = MyTemplates(directory=f"{webroot}", globals={"myglobal": "somevalue"})

Idk
  • 94
  • 1