Reputation: 685
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 find my templates.
My understanding is I could manually configure a list of directories for it to look for templates in, but I would like it to behave exactly like DTL behaves by default. (ie. look in the /templates directory). Basically, my app is structured the way it is suggested in the official tutorial, and I would like to use jinja without changing anything else. Is it possible?
Here's how my setings.py file looks now:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'APP_DIRS': True,
},
]
The error I get is TemplateDoesNotExist at /
and here is my directory structure:
mysite
mysite
myapp
templates
myapp
index.html
manage.py
please note that I am hoping not to use any external modules.
edit: as requested, here's the code calling the template:
def index(request):
return render(request, 'myapp/index.html')
Upvotes: 2
Views: 2769
Reputation: 1
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')
Upvotes: 0
Reputation: 11
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,
}
Upvotes: 1
Reputation: 308779
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
class MyJinja2(jinja2):
app_dirname = 'templates'
Then in your TEMPLATES
setting, use path.to.MyJinja2
instead of django.template.backends.jinja2.Jinja2
.
Upvotes: 1
Reputation:
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
Upvotes: 7