In previous chapters , The view function just returns the text directly , In fact, it is rarely used in the actual production environment , Because the actual pages are mostly styled HTML Code , This allows the browser to render very beautiful pages . At present, there are many template systems on the market , One of the most well-known and best used is DTL and Jinja2.
Django Template Language Abbreviations of three words , That is to say Django The template language comes with . Of course, it can also be configured Django Support Jinja2 Wait for other template engines , But as a Django Built in template language , and Django It can achieve seamless connection without some incompatibilities . So I suggest that you study well DTL.
DTL A template is a special syntax HTML file , This HTML Documents can be Django compile , You can pass parameters in , Dynamic data . After compiling , Generate an ordinary HTML file , Then send it to the client .
There are many ways to render a template . Here are two common ways .
render_to_string： Find the template , Then compile the template and render it as Python String format of . Last pass
HttpResponseClass is packaged as a
HttpResponseObject back to . The sample code is as follows ：
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)
HttpResponseThe object is completed in one step . The sample code is as follows ：
from django.shortcuts import render def book_list(request): return render(request,'list.html')
In the project
settings.py In file . There is one
TEMPLATES To configure , This configuration includes the configuration of the template engine , Configuration of template search path , Configuration of template context, etc . Template paths can be configured in two places .
DIRS： This is a list , All template paths can be stored in this list , Use later in view
render_to_string When rendering a template , Will find the template in the path of this list .
APP_DIRS： The default is
True, This is set to
True after , Will be in
INSTALLED_APPS Of installed
APP Under the
templates File plus find template .
render('list.html'). First of all
DIRS In this list, check whether there is this template under the path in turn , If there is , Just go back to . If
DIRS None of the paths in the list were found , Then the current view will be checked first
app Has it been installed? , If already installed , So first in the current
app Under the
templates Find template in folder , If not found , Then it will be installed in other
app Search for . If no path is found , Then a
TemplateDoesNotExist It's abnormal .