picture

Last time I introduced it to you Django The model and management tools that come with it , With this tool, you can automatically create a background management interface based on the model , So that the website manager can manage the website data more conveniently . With website data , So how to show it to users more conveniently and beautifully ? current Web The framework basically adopts MVC The architecture of , and Django A little change has been made on the basis of this architecture , namely MTV frame , there T That's what we're going to talk about today Django Template system based on XML ( Template ).

Know the template

First, the template is a text file , It defines the place holder and various basic logic used to standardize how the document should be displayed , Mainly used for dynamic generation HTML , That is, the template contains the required HTML The static part of the output and some special syntax describing the dynamic content to be inserted .Django A template system is built in by default DTL( Django template language ), It is enough to be used in general project development , Of course, you can also choose other third-party templates , commonly Django Projects can be configured with one or more template engines .

Use templates

Django The template system is actually Python A library , Just reference it in the code , You can create and use templates , But usually we use templates and views together . There are two steps to using templates :

  1. Create a template text , Or directly through the text path to create Template object , Of course, you can also create objects directly from strings in your code .
  2. call Template Object's render() Method , And pass in the corresponding <K,V> The variable object , In this way, the variables we configured in the template will be replaced with the corresponding values .

Now let's go ahead TestProject Under the project of polls Modify the code in the application , Enter into polls Under the table of contents , edit views.py The documents are as follows :

# views.py
from django.http import HttpResponsefrom polls.models import Choice, Questionfrom django.utils import timezone# Import template related libraries from django.template import Template, Context
# Before the change index Page rendering for template def index(request):    # Define templates    t = Template(' Hello <span style="color:#FF0000">{{ name }}</span>, This is a voting page .')    # Define the incoming object    c = Context({'name': ' Zhang San '})    # Back to the rendering template    return HttpResponse(t.render(c))
# …… Ignore some code

Modify and save , First by order python manage.py runserver 127.0.0.1:8080 Start a local server, And then by visiting URL http://127.0.0.1:8080/polls You can see the page we just modified , This is shown in the figure below :

 picture

Template syntax rules

Above we finished using templates to output data , So as to realize the separation of data and view . Now let's introduce the common syntax rules in the template in detail :

  1. Conditional judgment grammar Basic grammar :

     {% if Conditions %} #   Meet the conditions to show the content  {% endif %}
    # perhaps
    {% if Conditions 1 %} #   Meet the conditions 1 Exhibition {% elif Conditions 2 %} #   Meet the conditions 2 Exhibition {% else %} #   Not meeting the conditions 1 Conditions 2 The exhibition of {% endif %}

    in addition , Conditional judgment also supports and , or perhaps not Keyword to judge multiple variables , The template code is as follows :

     {% if  Variable 1 and  Variable 2 %} #    When variables 1 Or variables 2 by  true , Let's show the template here  {% endif %}

    Now we go on TestProject Under the project of polls Modify the code in the application , Enter into polls Under the table of contents , edit views.py The documents are as follows :

    # views.py
    from django.http import HttpResponsefrom polls.models import Choice, Questionfrom django.utils import timezone# Import template related libraries from django.template import Template, Context
    # Before the change index Page rendering for template def index(request):    # Define templates    t = Template('{%if name %} Hello <span style="color:#FF0000">{{ name }}</span>,{% else %} Hello, tourist , {% endif %} This is a voting page .')    # Define the incoming object    c = Context({'name': ' Zhang San '})    # Back to the rendering template    return HttpResponse(t.render(c))
    # …… Ignore some code

    Refresh the page , It's no different from the previous page , Because here we are Context It's coming in name Variable , If you don't pass name Variable , The results are as follows :

     picture

Loop iteration Syntax Same as most languages , The cycle is through for The syntax to achieve , In every cycle , The template system will render in {% for %} and {% endfor %} Between all the content .

 {% for book in book_list %}     <li>{{ book.name }}</li> {% endfor %}
# perhaps Can increase reversed Tag reverse iteration book_list
{% for book in book_list reversed %}     <li>{{ book.name }}</li> {% endfor %}

We continue to TestProject Under the project of polls Modify the code in the application , edit views.py The documents are as follows :

# views.py
from django.http import HttpResponsefrom polls.models import Choice, Questionfrom django.utils import timezone# Import template related libraries from django.template import Template, Context
# Before the change index Page rendering for template def index(request):    # Define templates    t = Template(' following {% for name in name_list %} <li>{{ name }}</li>  {% endfor %}   Please select ?')    # Define the incoming object    c = Context({'name_list': (' Zhang Yi ',' Zhang Er ',' Zhang San ')})    # Back to the rendering template    return HttpResponse(t.render(c))
# …… Ignore some code

Refresh the page , Here it is Context It's coming in name_list List variables , Use loop iteration Syntax , The results are as follows :

 picture

Special comparative grammar

 # ifequal/ifnotequal Syntax is used to more directly compare whether two variables are equal  {% ifequal user 'admin' %}     <h1> This is an administrator page !</h1> {% endifequal %}
# perhaps
{% ifnotequal user 'admin' %}     <h1> This is a tourist page !</h1> {% endifnotequal %}
# It's similar to conditional judgment grammar , {% ifequal %} Support optional {% else%} label {% ifequal user 'admin' %}     <h1> This is an administrator page !</h1> {% else %}     <h1> This is a tourist page !</h1> {% endifequal %}

We continue to TestProject Under the project of polls Modify the code in the application , edit views.py The documents are as follows :

# views.py
from django.http import HttpResponsefrom polls.models import Choice, Questionfrom django.utils import timezone# Import template related libraries from django.template import Template, Context
# Before the change index Page rendering for template def index(request):    # Define templates    t = Template('{% ifequal type 1 %} Hello <span style="color:#FF0000"> Administrators </span>, This is a management page .{% else %} Hello, tourist , This is a voting page .{% endifequal %}')    # Define the incoming object    c = Context({'type': 1})    # Back to the rendering template    return HttpResponse(t.render(c))
# …… Ignore some code

Refresh the page , Here it is Context It's coming in type Variable , When a variable is passed in 1 when , Get the management page , If not 1 It's the same page ,type Pass in 1 when , The results are as follows :

 picture

Template filter

Template filters can modify variables before they are displayed , The filter uses pipe characters . In addition, the filter pipe can be jacketed , That is, the output of one filter pipe can be used as the input of the next pipe .

  # {{ book_name }} Variables are filtered lower After processing , Document uppercase to lowercase .   {{ book_name|lower }}
 # Convert the first element of a variable to uppercase   {{ book_name|first|upper }}
 # Will intercept variables book_name Before 10 Bit character  {{ book_name|truncatewords: "10" }}

Except for the three above, of course , There are many other filters that will not be introduced one by one , You can search by yourself if you need to , In short, we can see that the filter greatly facilitates our flexible operation in the template .

Template inheritance

Template inheritance means that templates can be reused in this way , Since reuse is needed , Then we need to create a reusable template file first . First, in the root directory of the project , establish templates Directory is used to store template files , And create it in this directory common.html Files are used for reuse , Write the following code :

  <html>    <head>        <title> Public pages </title>    </head>
   <body>        <h1> Hello <span style="color:#FF0000">{{ name }}</span>, This is a public page !</h1>        {% block mainbody %}        <p> Original page </p>        {% endblock %}    </body>  </html>

And then create index.html Template file , And write the code in the file , Realize to common.html The use of template files .

    {% extends "common.html" %}
   {% block mainbody %}    <p> It's inherited here common.html Templates !</p>    {% endblock %}

Finally, modify the project directory ,TestProject/settings.py The configuration file , Find... In the configuration file TEMPLATES object , And we're modifying it DIRS The configuration path of is as follows :

    TEMPLATES = [        {            'BACKEND': 'django.template.backends.django.DjangoTemplates',            'DIRS': [BASE_DIR+"/templates",],     #  Modify the template configuration path             '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',                ],            },        },    ]

Okay , Now the template configuration is complete , The next step is to modify our rendering page , Open again polls Under the application of views.py, Comment the home page code , Then rewrite the home page as follows :

    from django.shortcuts import render    from django.http import HttpResponse    from polls.models import Choice, Question    from django.utils import timezone    from django.template import Template, Context
   # Comment on the original code    #def index(request):    #    return HttpResponse(" Hello , This is a voting page .")    #    t = Template(' Hello <span style="color:#FF0000">{{ name }}</span>, This is a voting page .')    #    c = Context({'name': ' Zhang San '})    #    return HttpResponse(t.render(c))
   # Add new code    def index(request):        context = {}        context['name'] = ' Zhang San '        # Return to the home page after template rendering        return render(request, 'index.html', context)

Modified to complete , Finally, by visiting URL http://127.0.0.1:8080/polls You can see the page we just modified , This is shown in the figure below :

 picture

In this way, the reuse of templates can be better realized .

  1. The template contains

    This is through {% include %} Grammar tags , Introduce one template into the content of another or more templates , The code is as follows :

      {% include "common.html" %}

summary

This article introduces Django Template Template Foundation , The separation of data and presentation can be realized through the application template , In this way, we can display the front end more flexibly . Of course, it's just a brief introduction to the template , There are more complex ways to use it , I'll give you an in-depth introduction in the future .

Reference resources

Django Chinese official website :https://docs.djangoproject.com/zh-hans/2.2

Sample code :https://github.com/JustDoPython/python-100-day

Series articles


The first 123 God :Web Development Django Management tools

The first 122 God :Flask unit testing

The first 121 God : Decision trees for machine learning
from 0 Study Python 0 - 120 Summary of the grand collection