How to make Django template raise an error if a variable is missing in context

后端 未结 2 406
时光说笑
时光说笑 2021-01-01 10:45

I\'m using Django templates in a non-Django project and I want to make sure that my templates contain no references to variables that are not in context and for that I need

2条回答
  •  没有蜡笔的小新
    2021-01-01 10:56

    You can easily switch template backend to jinja2 to get this.

    Step 0: add jinja2 to your Pipfile or requirements.txt

    Step 1: in settings.py change TEMPLATES to look like this:

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.jinja2.Jinja2',
            'APP_DIRS': True,
            'OPTIONS': {
                'undefined': jinja2.StrictUndefined
            },
        },
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            ...
    

    Step 2: rename your templates directory to jinja2

    Step 3: (maybe not needed, depends on what you use in templates) update your templates according to https://jinja.palletsprojects.com/en/2.10.x/switching/#django

提交回复
热议问题