First Step: Configure
1. Create the template catalog templates in the project.
2. Modify the dirs value of the Templates configuration item in the settings.py configuration file:
TEMPLATES = [
{
' Backend ': ' Django.template.backends.django.DjangoTemplates ',
' DIRS ': [Os.path.join (Base_dir, ' templates ')], # Modified here
' 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 ',
],
},
},
]
Step two: Define the template
1. Create a new template file in the templates directory, such as index.html
<! DOCTYPE html>
<meta charset= "UTF-8" >
<title>Title</title>
<body>
</body>
Step Three: Template rendering
The invocation template is divided into two steps:
1. Find template Loader.get_template (relative path to template file in template directory), return template object
2 Render Template Template object. Render (Context=none, Request=none), returns the rendered HTML text string context is the template variable dictionary, the default value is None request is the requested object, the default value is None
Way One:
From django.http import HttpResponse
From django.template Import Loader
def index (Request):
# 1. Get the template
Template=loader.get_template (' index.html ')
context={' city ': ' Beijing '}
# 2. Render Template
Return HttpResponse (Template.render (context))
Way Two (recommended):
Render (Request object, template file path, template data dictionary)
From django.shortcuts Import Render
def index (Request):
context={' city ': ' Beijing '}
return render (Request, ' index.html ', context)
Different template statements compared to flask
Lists and dictionaries can only be manipulated by point syntax
Note: Operators cannot be close to variables or constants on either side, and must have spaces.
{% If a = = 1%} # correct
Multi-line comments
{% Comment%}
...
{% Endcomment%}
Template inheritance: {{block.super}} to get the contents of a block in the parent template
The template used in Django