Starting with Django 1.8, you can choose Jinja2 as the template engine #djangoja

I wrote this article while attending TokyoDjangoMeetup # 3.

Starting with Django 1.8, you can choose Jinja2 as your template engine. To set it, just write TEMPLATES in the configuration file as follows.

settings.py


TEMPLATES = [
    {
        #↓ Rewrite the default value to this
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            # context_Do not use it because it does not work if there are processors(See below)
            #'context_processors': [
            #    'django.template.context_processors.debug',
            #    'django.template.context_processors.request',
            #    'django.contrib.auth.context_processors.auth',
            #    'django.contrib.messages.context_processors.messages',
            #],
        },
    },
]

Jinja2 is not included with Django, so please install Jinja2 separately with pip install Jinja2.

In settings.py generated by django-admin start project, there is context_processors in'OPTIONS', but if you use Jinja2 with this left, the following error will occur. [^ 1]

Exception Type: TypeError
Exception Value: 
__init__() got an unexpected keyword argument 'context_processors'

You can use the item ʻenvironment instead of context_processors. Write ʻapp / jinja2.py with the following contents,

jinja2.py


from __future__ import absolute_import  # Python 2 only

from jinja2 import Environment
from datetime import datetime


def environment(**options):
    env = Environment(**options)
    #This is context_Instead of processors
    env.globals.update({
        'greeting': u"HELLO!",
        'imananji': datetime.now, #Pass a callable object if you want the result every time you load the page
    })
    return env

If you write ʻenvironment as follows, you can use {{greeting}} , {{imananji ()}} `in the template.

settings.py


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            # 'app'Part depends on the application configuration
            'environment': 'app.jinja2.environment',
        },
    },
]

[^ 1]: ... Sample code in official documentation casually 'context_processors' Is erased: cry:

Recommended Posts

Starting with Django 1.8, you can choose Jinja2 as the template engine #djangoja
You can read the analog meter with the example MNIST.
You can read the analog meter with the example MNIST.
Jinja2 | Python template engine
Web application with Python3.3.1 + Bottle (1) --Change template engine to jinja2
Can you delete the file?
If you know Python, you can make a web application with Django
I compared while reading the documentation to use Jinja2 with Django