Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jinja2 as a templating engine in Django 1.8

I have been looking on how to use jinja2 in django 1.8, but there is no complete source for using django with jinja2. I was wondering if you guys knew the process for using jinja2 in django. I have looked through the the official documentation and I have looked at the following question: How to setup django 1.8 to use jinja2?

but none of them clearly explain how to use jinja2 in an put-togther manner. I just started using django and don't know all the lingo in the docs. I would really appreciate the help.

like image 945
biiiju Avatar asked Jun 08 '15 05:06

biiiju


People also ask

What is Jinja2 template 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.

Is Django using Jinja2?

The Django template language doesn't have an equivalent of Jinja2 tests.

What is the difference between Jinja and Jinja2?

Jinja, also commonly referred to as "Jinja2" to specify the newest release version, is a Python template engine used to create HTML, XML or other markup formats that are returned to the user via an HTTP response.


2 Answers

Frist you have to install jinja2:

$ pip install Jinja2 

Then modify your TEMPLATES list in the settings.py to contain the jinja2 BACKEND :

TEMPLATES = [      {         'BACKEND': 'django.template.backends.jinja2.Jinja2',         'DIRS': [os.path.join(BASE_DIR, 'templates/jinja2')],         'APP_DIRS': True,         'OPTIONS': {'environment': 'myproject.jinja2.Environment',},      },     {         'BACKEND': 'django.template.backends.django.DjangoTemplates',         'DIRS': [],         'APP_DIRS': True,         'OPTIONS': {         'context_processors': [             'django.template.context_processors.debug',             'django.template.context_processors.request',             'django.contrib.auth.context_processors.auth',             'django.contrib.messages.context_processors.messages',            ],         },     }, ] 

where templates/jinja2 is the directory with your jinja2 template files.

And in your views.py file:

from __future__ import absolute_import  # Python 2 only from jinja2 import Environment from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import reverse  def environment(**options):     env = Environment(**options)     env.globals.update({        'static': staticfiles_storage.url,        'url': reverse,     })     return env 

This makes static and url available in your Jinja2 templates.

P.S. For more details see this article.

like image 160
doru Avatar answered Oct 02 '22 21:10

doru


Took me quite some time to figure out everything, answers here weren't all that helpful.

doru's answer is closest to truth but is incomplete.

How to use jinja as templating language:

1.Create jinja2.py file in your project folder. This is required to modify the default jinja2 Environment (in our case, passing some additional global variables).

location: {root}/main/jinja2.py:

from __future__ import absolute_import  # Python 2 only from jinja2 import Environment from django.contrib.staticfiles.storage import staticfiles_storage from django.core.urlresolvers import reverse  def environment(**options):     env = Environment(**options)     env.globals.update({        'static': staticfiles_storage.url,        'url': reverse,     })     return env 

2.Add jinja2 backend to django project settings file, including our modified environment.

TEMPLATES = [     {         'BACKEND': 'django.template.backends.jinja2.Jinja2',         'DIRS': [],         'APP_DIRS': True,         'OPTIONS': {             'environment': "main.jinja2.environment",         },     },     ... ] 

3.Now you no longer need to import jinja2 anywhere, in your views, you will be using jinja templates through django just like django templates:

from django.shortcuts import render  def index(request, **kwargs):     return render(request, "index.html.j2", {'title': 'MyTitle', 'text': "MyText"}) 

And finally, with APP_DIRS set to True jinja will search templates in all installed apps jinja2 directories. (unlike DTL that searches for templates folder). If you want to change that behavior, or want some extra tweaking, like extension match, filtering or global variables, you should look at django-jinja extension.

You may also provide additional directories to search for templates via TEMPLATES['DIRS'] option of settings.

like image 32
IvanX Avatar answered Oct 02 '22 20:10

IvanX