[Django]-How to use jinja2 in Django 3.1

1๐Ÿ‘

โœ…

You can use multiple engines, but then the directories should be non-overelapping, or you use the engines with a given priority, if you specify with the DIRS setting [Django-doc] what directories belong to which template. But here both are the same, so that means Django will always select the first one.

You thus specify:

# settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    }
]

We thus do not add any items to the DIRS setting for the DjangoTemplates.

1๐Ÿ‘

here are docs: https://niwinz.github.io/django-jinja/latest/

install jinja2

pip install django-jinja

add into INSTALLED_APPS

INSTALLED_APPS = (
         .......
    'django_jinja',
         .......
)

add into template engines list:

TEMPLATES = [
    {
        "BACKEND": "django_jinja.backend.Jinja2",
        "APP_DIRS": True,
        "OPTIONS": {
           "match_extension": ".jinja",
        }
     },
     {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True
     },
]
๐Ÿ‘คapet

Leave a comment