Introduction to Django templates

Preface

There are a lot of templating systems on the market today, and the best known and used are DTL and Jinja2. DTL is an abbreviation of the three words Django Template Language, which is the template language that comes with Django. Of course, you can also configure Django to support other template engines such as Jinja2, but as Django’s built-in template language, and Django can achieve seamless integration without creating some incompatibilities.

Differences between DTL and ordinary HTML files

A DTL template is an HTML file with a special syntax. This HTML file can be compiled by Django and can be passed parameters in to achieve data dynamics. After compilation, a normal HTML file is generated and sent to the client.

Rendering templates

There are several ways to render templates. Two common ways are described here.

  • render_to_string: find the template, then compile the template and render it into Python string format. Finally, it is wrapped into an HttpResponse object by the HttpResponse class and returned back.
 from django.template.loader import render_to_string
 from django.http import HttpResponse

 def book_detail(request,book_id):
     html = render_to_string("detail.html")
     return HttpResponse(html)
  • The above way is convenient enough though. But django also provides a much easier way to render templates directly into strings and wrap them into HttpResponse objects in one step.
 from django.shortcuts import render

 def book_list(request):
     return render(request,'list.html')

Template lookup path configuration

In the settings.py file of the project. There is a TEMPLATES configuration, which contains the configuration of the template engine, the configuration of the template lookup path, the configuration of the template context, etc. Template paths can be configured in two places.

  1. DIRS: This is a list where all the template paths can be stored. When rendering templates with render or render_to_string in the view later, the templates will be found in the paths of this list.
  2. APP_DIRS: default is True, after this is set to True, it will find templates in the installed APP templates file under INSTALLED_APPS.
  3. Search order: For example, code render(‘list.html’). First, it will find whether there is this template under the path in the DIRS list, if there is, it will return. If the template is not found in all paths in DIRS list, then it will first check whether the app where the view is currently installed, if it is installed, then it will first look for the template in the templates folder under the current app, if it is not found, then it will look for it in other apps that are already installed. If it is not found in all paths, then a TemplateDoesNotExist exception will be thrown.

Leave a Reply