Using Jinja2 with Django, upload tag not working

I am building a Django app and decided to use Jinja2 for my templating engine. I noticed that after I switched from the Django, the built-in template engine Jinja2, the keyword load

is not running, for example {% load static %}

. This is used for loading static files like CSS. Is there a Jinja way to do this in Django?

TemplateSyntaxError in / app /
Unknown "load" tag.

From settings.py:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.jinja2.Jinja2',
    'DIRS': [
        os.path.join(BASE_DIR, 'app/templates/jinja2'),
    ],
    'APP_DIRS': True,
    'OPTIONS': {
        'environment': 'my_project.jinja2.environment',
    },
},

      

Django: 1.11
Jinja2: 2.9.6

+3


source to share


2 answers


This is explained in the manual section for Jinja2 in the django template description

The default configuration is purposefully kept to a minimum. If the template is rendered with a request (for example, when using render ()), the Jinja2 Backend adds the globals, csrf_input and csrf_token request to context. Also, this backend does not create Surrounded by Django. It is unaware of Django filters and tags. In order to use Django specific APIs, you must configure them in the environment.



Yes, {% load static%} doesn't exist, but there is a simple work around. Again, an example is from the link

from __future__ import absolute_import  # Python 2 only

from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reverse

from jinja2 import Environment


def environment(**options):
    env = Environment(**options)
    env.globals.update({
        'static': staticfiles_storage.url,
        'url': reverse,
    })
    return env

      

+2


source


Actually, this is the expected behavior in Jinja2. This is because Jinja2 tags are not loaded from the template page, but extensions are added to the Jinja2 env at build time. When it starts up (and env is created) you cannot add additional extensions.



You can see more information on this here: http://jinja.pocoo.org/docs/2.9/extensions/#adding-extensions

+1


source







All Articles