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
The first step to use Jinja in Django is to install the core package with the pip command: python3 -m pip install Jinja2 . Note the package name is Jinja2 while the latest Jinja version is 3.0.
from_string . Jinja 2 provides a Template class that can be used to do the same, but with optional additional configuration. Jinja 1 performed automatic conversion of bytes in a given encoding into unicode objects.
Jinja works with Python 2.7. x and >= 3.5. If you are using Python 3.2 you can use an older release of Jinja (2.6) as support for Python 3.2 was dropped in Jinja version 2.7. The last release which supported Python 2.6 and 3.3 was Jinja 2.10.
Jinja is a web template engine for the Python programming language. It was created by Armin Ronacher and is licensed under a BSD License. Jinja is similar to the Django template engine but provides Python-like expressions while ensuring that the templates are evaluated in a sandbox.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With