Django The template layer of is responsible for rendering content to the browser , Simply put, it is used to put HTML And other static web pages , Easy to manage the front-end interface and django Call itself .
First, in the manage.py The same as creating in the directory templates Folder , For HTML Wait for the documents .
And then we need to tell django Where to put the template , So you also need a configuration file setting.py Configure the path of the corresponding template layer .
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# Configure the path of the template layer , Project absolute path + Template layer file name = Template layer path
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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',
],
},
},
]
After configuring the path , You can go to templates Create one under the folder test_html.html
The contents are as follows :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3> Formwork layer !!!hello world !!</h3>
</body>
</html>
Just put something in it .
Then configure the corresponding routes and views
The configuration view
views.py:
from django.shortcuts import render
from django.http import HttpResponse
def test_html(request):
return render(request, "test_html.html")
Due to the use of template layer , Therefore, the code corresponding to the call will be much simpler .
Configure the routing
urls.py:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path("test_html", views.test_html),
]
Then run the server .
Open the browser and enter http://127.0.0.1:8000//test_html
The following shows that the template layer configuration is successful !
django The template layer of web page variable data transmission is very convenient , direct { { Variable name }} To transmit , and jsp in java Variables are transferred to the web page , Of course django The template layer can also be embedded python Code .
django The data types that can be passed in are as follows :
str、int、list、tuple、dict、func、obj
The methods passed are enumerated :
{ { Variable name }}
{ { Variable name .index}}
{ { Variable name .key}}
{ { Variable name . Method }}
{ { Function name }}
Next, take an example to understand how to operate .
First, configure the view function view.py:
from django.shortcuts import render
from django.http import HttpResponse
def hello():
return "hello world"
class dog():
def say(self):
return "hellllllllll"
def test_html(request):
dic = {
}
dic["int"] = 88
dic["str"] = "good"
dic["list"] = ["A", "B", "C"]
dic["dicts"] = {
"A":555, "B":666}
dic["func"] = hello
dic["obj"] = dog()
return render(request, "test_html.html", dic)
Data transmission can only be transmitted in the form of a dictionary , We have transmitted a int、 One str、 One list、 A dictionary 、 A function and an object used to .
Then configure the web page content of the template layer ,templates Under folder test_html.html as follows :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3> Formwork layer !!!hello world !!{
{username}}</h3>
<table>
<tr>
<td>int</td>
<td>{
{int}}</td>
</tr>
<tr>
<td>str</td>
<td>{
{str}}</td>
</tr>
<tr>
<td>list_one</td>
<td>{
{list.1}}</td>
</tr>
<tr>
<td>dicts</td>
<td>{
{dicts.A}}</td>
</tr>
<tr>
<td>func</td>
<td>{
{func}}</td>
</tr>
<tr>
<td>obj</td>
<td>{
{obj.say}}</td>
</tr>
</table>
</body>
</html>
You should know how to call various types by looking at the code .
Configure the routing urls.py:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path("test_html", views.test_html),
]
Then run the server , visit http://127.0.0.1:8000//test_html
You can see that all variables can be transferred . The most important thing to note is that the index of the list element is Variable name .index( Reference no. ) To index .
python If the code is embedded , The grammar should be similar , Only need <%%> Input in python The code can call .
Let's continue with the configuration just now , Only need to test_html.html Add python You can see the effect by calling the code .
test_html.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3> Formwork layer !!!hello world !!{
{
username}}</h3>
<table>
<tr>
<td>int</td>
<td>{
{
int}}</td>
</tr>
<tr>
<td>str</td>
<td>{
{
str}}</td>
</tr>
<tr>
<td>list_one</td>
<td>{
{
list.1}}</td>
</tr>
<tr>
<td>dicts</td>
<td>{
{
dicts.A}}</td>
</tr>
<tr>
<td>func</td>
<td>{
{
func}}</td>
</tr>
<tr>
<td>obj</td>
<td>{
{
obj.say}}</td>
</tr>
</table>
{
%if dicts.A > 100 %}
hello world
{
%else %}
good mornings world
{
%endif %}
{
% for i in list%}
{
{
i}}
{
%empty%}
Empty
{
%endfor %}
</body>
</html>
Run the server to get :
The bottom line is embedded python What the code does .
Template filter , The output display of variables can be changed through filters
grammar :{ { Variable | filter }}
Just take an example .
views.py:
from django.shortcuts import render
from django.http import HttpResponse
def hello():
return "hello world"
class dog():
def say(self):
return "hellllllllll"
def test_html(request):
dic = {
}
dic["int"] = 88
dic["str"] = "good"
dic["list"] = ["A", "B", "C"]
dic["dicts"] = {
"A":555, "B":666}
dic["func"] = hello
dic["obj"] = dog()
dic["script"] = "<script>alert(6666)</script>"
return render(request, "test_html.html", dic)
test_html.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3> Formwork layer !!!hello world !!{
{username}}</h3>
<table>
<tr>
<td>int</td>
<td>{
{int | add:"50"}}</td>
</tr>
<tr>
<td>str</td>
<td>{
{str | upper}}</td>
</tr>
<tr>
<td>list_one</td>
<td>{
{list.1}}</td>
</tr>
<tr>
<td>dicts</td>
<td>{
{dicts.A}}</td>
</tr>
<tr>
<td>func</td>
<td>{
{func}}</td>
</tr>
<tr>
<td>obj</td>
<td>{
{obj.say}}</td>
</tr>
<tr>
<td>script</td>
<td>{
{script | safe}}</td>
</tr>
</table>
</body>
</html>
Route unchanged , It is the same as the one in the previous example .
Run the server , There should be a pop-up window , then int Will add 50,str Will be capitalized .
When surfing the Internet at ordinary times , We can find that the pages in many websites are similar , For example, in the same website , The top navigation bar and the bottom copyright block are the same , Only the core content in the middle of the web page has changed , In order to improve the reusability of code , Improve development efficiency ,django It can realize the integration and rewriting of template layer , Similar to object-oriented operations .
The following is an example to intuitively experience .
First, configure the routing , Here we need to configure two routes , Enter the parent page and the child page respectively
urls.py:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path("father", views.father),
path("child", views.child)
]
Then we configure the corresponding view function :
views.py:
from django.shortcuts import render
from django.http import HttpResponse
def father(request):
dic = {
}
dic["a"] = 10
return render(request, "father.html", dic)
def child(request):
return render(request, "child.html")
Finally, we need to configure the corresponding HTML, stay templates Folder to configure the parent page and the child page HTML.
django The inheritance modifiable part is the following format :
{
%block Block name %}
##########
{
%endblock%}
If something in the block name is overwritten , The rest will be inherited intact .
that father.html as follows :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
2022----------------------------------
<br>
{%block info %}
This is the home page
{%endblock %}
</body>
</html>
child.html as follows :
{
% extends "father.html"%}
{
%block info%}
Hello , welcome , Thank you for your patronage
{
%endblock%}
among {% extends “father.html”%} Represents inheritance father,html The content of , And then it rewrites info What's in the block , Therefore, the original content will be overwritten , Therefore, the results after the server is finally started are as follows :
It can be found that it is only modified block info The content in .
It is worth noting that , When the template inherits , The variables passed in from the template cannot be inherited