I compared while reading the documentation to use Jinja2 with Django

This article is Day 16 of Django Advent Calendar 2016.

What is Jinja2

Simply put, it's a Python template engine. Official page: http://jinja.pocoo.org/ Inspired by Django's template engine, it looks the same as Django's default template engine. Jinja2 is more feature-rich than Django's template engine, and can be used for other purposes such as LaTex and email, rather than a template engine dedicated to writing HTML and XML.

Officially supported since 1.8 on Django. (Installation of library is required)

By the way, the origin of the name is If you translate the shrine into English, Temple, Template and Temple have similar pronunciations → It seems to be Jinja w

How I decided to investigate

I'm new to Django, so I've never used Jinja2 with Django asking if I should use the default template engine for the time being. I've used it in Other Uses (I'm sorry for my article w), but I haven't done anything special, so I read the documentation so much. There is no such thing.

~~ Rails is more accustomed to web framework development than Django, so I really want to use Ruby Slim ~~ There is a more convenient template engine to make development easier. I wanted to use it if possible, so this time I decided to investigate Jinja2 focusing on the use in Django.

It seems that Django also has a slim-like template engine, but I stopped it because there is little information and it seems to be troublesome to look up.

** This article only writes about Django, so I won't cover it for any other purpose. ** **

Execution environment

Actually replacing the Django template with Jinja2 seemed to be difficult, so this time I just replaced a small part of the existing project with a trial. As I will write in the next introduction item, the default template engine and Jinja2 were mixed in one project. ** Python 3.3 and above does not seem to be fully supported **, so you should be careful if you are using 3.4 or above. However, since the test itself has passed, even if there are bugs, only small ones will be. http://jinja.pocoo.org/docs/dev/intro/#experimental-python-3-support

Introduction

Rewrite TEMPLATE in Django's settings.py as follows: By default, Jinja2 will look for template files in the jinja2 directory, so switching to Jinja2 just for BACKEND will not work as usual. It seems that it is necessary to change the templates directory name of each application to jinja2 or explicitly specify it with DIRS. In the example below, the Jinja2 setting is added to the usual (?) Setting.

In my local development environment, I put django_debug_toolbar etc., but in order to pass the path to the templates of these libraries, I had to put the usual template settings as well. In a production environment, these libraries are not used, and only the templates defined by themselves are used (probably), so it seems that only the Jinja2 settings are sufficient.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [os.path.join(BASE_DIR, 'templates/jinja2')],
        'APP_DIRS': True,
    },
    {
        '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',
            ],
        },
    },
]

Differences from Django

The documentation is extensive, but there are many parts that aren't relevant for use as Django's template engine, so for now, just take a look at the URL below and you'll see what you can do. http://jinja.pocoo.org/docs/dev/templates/#synopsis

Although it is called Django Inspire, there are many differences in detailed specifications, so I will introduce only the major differences.

Difference in description when executing method

With JinJa2, you can write processing like Python even on a template. As shown below, Django does not have (), but Jinja2 has (). Django: {% for page in user.get_created_pages %} Jinja2: {% for page in user.get_created_pages() %} Thanks to this, you can do something like Add order_by to your Django model on the template side. However, I don't think it's cool to squeeze such a description on the template side.

macro

http://jinja.pocoo.org/docs/dev/templates/#macros In Django, if you want to do something other than the processing provided from the beginning on the template, I think you defined your own template tag, but in Jinja2, you define it using something called macro. The macro defined in the template can be reused by using call. I will omit the details w

You can use various operators and filters (template tags?)

http://jinja.pocoo.org/docs/dev/templates/#list-of-builtin-filters There are surprisingly many filters. A quick look, Python arrays, strings, and numeric objects can be used or the methods they have are relatively usable.

http://jinja.pocoo.org/docs/dev/templates/#math I use django-mathfilter when I want to perform four arithmetic operations on a template with Django, but Jinja2 doesn't seem to need it. It's sober, but I'm happy. There are also many comparison operators.

It's overwhelmingly easier than creating and using template tags by yourself.

Handling of variables

For example, when you want to display the following variables in a template,

foo = {"bar": 1}

For Django's default template

foo.bar

Therefore, you cannot write foo ["bar "], but in the case of Jinja2, you can also use foo ["bar "]. I'm also happy because it always felt strange to access dict variables with dots.

Handling of global variables

http://qiita.com/ryu22e/items/e50f8a3fbd6fe836c1b4 I will not write it because some people have already written the article. I think that context_processor is applicable to Django's default template engine, but I'm not sure if the ability to set global variables is the advantage of Jinja2 because I have never made it myself.

Summary

It has more features than I expected, and it has become a rough article.

It's very versatile and I want to use it right away, but while it's called Django Inspire, there are many minor differences, and I got the impression that replacing an existing project with Jinja2 seems a bit annoying. When switching to slim with Rails, there is a conversion command, so it was relatively easy to switch, but Jinja2 seems to be impossible unless you check everything properly. I would like to try it when creating a new application.

Also, I don't think it's good to stuff the logic on the template side or touch the data in the first place, so I thought that I had to be especially careful when using Jinja2. The same thing is written in the document. http://jinja.pocoo.org/docs/dev/faq/#isn-t-it-a-terrible-idea-to-put-logic-into-templates

Recommended Posts

I compared while reading the documentation to use Jinja2 with Django
[Python] I want to use the -h option with argparse
[Django] I made a field to enter the date with 4 digit numbers
I want to use the Django Debug Toolbar in my Ajax application
I changed the jwt token generator to simplejwt with Django Rest Auth.
I tried to implement reading Dataset with PyTorch
I tried to use lightGBM, xgboost with Boruta
The easiest way to get started with Django
I want to use MATLAB feval with python
I tried to optimize while drying the laundry
I tried to save the data with discord
Specify the Python executable to use with virtualenv
I wanted to play with the Bezier curve
The easiest way to use OpenCV with python
I want to use Temporary Directory with Python2
I don't want to use -inf with np.log
I want to use ip vrf with SONiC
I want to use the activation function Mish
I tried to learn the sin function with chainer
I tried to create a table only with Django
I want to scroll the Django shift table, but ...
Use Gentelella with django
I tried to touch the CSV file with Python
I wanted to use the Python library from MATLAB
I want to inherit to the back with python dataclass
Specify MinGW as the compiler to use with Python
Use LESS with Django
Transit to the update screen with the Django a tag
I tried to solve the problem with Python Vol.1
I just wanted to extract the data of the desired date and time with Django
I want to use the R dataset in python
I wrote you to watch the signal with Go
I tried to find the entropy of the image with python
I want to use the latest gcc without sudo privileges! !!
I want to use R functions easily with ipython notebook
I tried to simulate how the infection spreads with Python
I wanted to solve the Panasonic Programming Contest 2020 with Python
Why can I use the module by importing with python?
It's too easy to use an existing database with Django
I tried to find the average of the sequence with TensorFlow
I tried to notify the train delay information with LINE Notify
I want to make a blog editor with django admin
I want to use only the normalization process of SudachiPy
I want to change the Japanese flag to the Palau flag with Numpy
Understanding how to use Jinja2 makes development with Flask smarter
I noticed while trying to run ninix-aya with Docker (Part 3)
I want to use a virtual environment with jupyter notebook!
I didn't know how to use the [python] for statement
I captured the Touhou Project with Deep Learning ... I wanted to.
I tried to divide the file into folders with Python
I tried to summarize how to use the EPEL repository again
I compared blade and jinja2
Use prefetch_related conveniently with Django
To celebrate the release of Django 3.0, I tried ASGI, the spiritual successor to WSGI, but I couldn't use websocket.
I compared the speed of Hash with Topaz, Ruby and Python
I tried to describe the traffic in real time with WebSocket
I tried to solve the ant book beginner's edition with python
Repeat with While. Scripts to Tweet and search from the terminal
I want to use a wildcard that I want to shell with Python remove
I want to know the weather with LINE bot feat.Heroku + Python
[September 2020 version] Explains the procedure to use Gmail API with Python