Skip to content Skip to sidebar Skip to footer

How To Setup Django 1.8 To Use Jinja2?

So, now that django officially supports Jinja 2 as a templating engine, I hoped enabling it would be as simple as switching a line in config. But when I do that, jinja fails to fin

Solution 1:

The Jinja2 template backend searches the jinja2 folder in the app directories, instead of templates. This has the advantange of preventing DTL and Jinja2 templates from being confused, especially if you enable multiple templating engines in your project.

I would recommend sticking with the default behaviour, and renaming your templates directory to jinja2. However, if you must change it, you could create a custom backend, and set app_dirname.

from django.template.backends.jinja2 import Jinja2

classMyJinja2(jinja2):
    app_dirname = 'templates'

Then in your TEMPLATES setting, use path.to.MyJinja2 instead of django.template.backends.jinja2.Jinja2.

Solution 2:

Another thing to consider is that render_to_response can not take a context_instance for jinja2 templates

https://github.com/django-haystack/django-haystack/issues/1163

I believe, but I might be wrong, but I think jinja2 can't share the same directory as the django templates. try

TEMPLATES = {
    'BACKEND': 'django.template.backends.jinja2.Jinja2',
    'DIRS': [os.path.join(PROJECT_ROOT, 'jinja2'),],
    'APP_DIRS': True,
}

Solution 3:

The Jinja template folder for app dirs defaults to jinja2 not the standard templates folder.

So try the following directory structure and Django will locate your Jinja templates:

mysite mysite myapp jinja2 myapp index.html manage.py

And instead of: return render(request, 'myapp/index.html') you should write: return render(request, 'index.html')

Post a Comment for "How To Setup Django 1.8 To Use Jinja2?"