andrew
andrew

Reputation: 5559

Using Jinja2 with Django, load tag does not work

I'm building a Django app and chose to use Jinja2 for my templating engine. I noticed after I switched from Django's built in templating engine to Jinja2 the load keyword would not work, ex: {% load static %}. This is used to load static files like CSS. Is there a Jinja workaround for this in Django?

TemplateSyntaxError at /app/
Encountered unknown tag 'load'.

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

Upvotes: 10

Views: 13200

Answers (2)

e4c5
e4c5

Reputation: 53734

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

The default configuration is purposefully kept to a minimum. If a template is rendered with a request (e.g. when using render()), the Jinja2 backend adds the globals request, csrf_input, and csrf_token to the context. Apart from that, this backend doesn’t create a Django-flavored environment. It doesn’t know about Django filters and tags. In order to use Django-specific APIs, you must configure them into the environment.

Yes, {% load static %} does not exists, but there is a simple work around. Again, the example is from the reference

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

Upvotes: 8

Kostas Livieratos
Kostas Livieratos

Reputation: 1067

Actually, that is expected behavior in Jinja2. That is because with Jinja2 tags are not loaded from the template page, but extensions are added to the Jinja2 env during the creation. When it starts running (and the env is created), you cannot add more extensions.

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

Upvotes: 0

Related Questions