Templates can be generated dynamically HTML Webpage , from HTML Code and special template syntax .
Django The project template file is placed in templates
In the catalog , Use PyCharm Created Django The project will be settings In the document TEMPLATES
The template position is automatically configured in
Use... In view functions render() Function can render pages , Need to request 、 Template path and dynamic data are used as parameters .
from django.shortcuts import render
def hallo(request):
# Business code
# return render Function rendered pages
return render(request, template_path, context)
HTML Template through {{ Variable name }}
To render the dynamic data from the back end
Use Pycharm Create project django_templates
The template path will be customized and configured
Created from the command line django project , You need to add the template path manually
Created from the command line zulu application
python3 manage.py startapp zulu
stay zulu app Internal increase urls.py, To configure a tango/
route
from django.urls import path
from .views import *
urlpatterns = [
path('tango/', Tango.as_view()),
]
In the project root path urls.py Middle configuration zulu app Mapping
from django.urls import path, include
from zulu import urls as zulu
urlpatterns = [
path('admin/', admin.site.urls),
path('zulu/', include(zulu))
]
stay zulu app Of views.py Write the view class in , And bind the template
from django.shortcuts import render
from django.views.generic import View
# Create your views here.
class Tango(View):
def get(self, request):
context = {'info': 'This is Tango 5'}
return render(request, 'tango.html', context=context)
Under the project root path templates Add a template under the folder tango.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Zulu</title>
</head>
<body>
<h1>{{info}}</h1>
</body>
</html>
start-up Django application , Enter... In the browser /zulu/tango/
The dynamic data in the page is successfully rendered .
Variables and labels
Variable usage {{ }}
Double curly braces indicate , If the data passed from the back end to the front end {{ info }}, Built in label types , Use {% %}
In the form of braces and a percent sign . Common built-in tags are as follows :
for Circular labels are commonly used in templates , It is often used to traverse the data in the output list ,for Loop tags also have some common variables , Such as index, etc