Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 329
andrew Avatar asked May 30 '17 21:05

andrew


People also ask

Can I use Jinja with Django?

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.

What is the difference between Jinja and Jinja2?

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.

Does Jinja2 work with Python 3?

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.

What is Jinja tag in Django?

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.


1 Answers

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
like image 131
e4c5 Avatar answered Oct 31 '22 10:10

e4c5