🍖 Template layer of Django framework

Time:2021-6-7

1、 Two template methods

  • Variable correlation:{{ }}

  • Logical correlation:{% %}

2、 Notes

  • Comments are the mother of code:{# #}

3、 Value transfer in template grammar

1. Value transfer of basic data type in Python

def test_func(request):
    S = "Hello, big star!"
    i = 1314520
    f = 1.75
    l = [1,2,3,4,5]
    d = {"name":"shawn","age":23}
    t = (2,3,4,5,5)
    se = {3,4,5,'rr'}
    b = True
    
    #Value transfer method 1: use the dictionary format to transfer one by one
    return render(request,'test.html',{'strs':s,'ints':i,'lists':l,...})
    #Value transfer method 2: use locales() to transfer all variable names in the current namespace to the micro page
    return render(request,'test.html',locals())
{{ s }}
{{ i }}
{{ f }}
{{ l }}
{{ d }}
{{ t }}
{{ se }}
{{ b }}

image-20210318194630391

2. Transfer of function and class

def test_func(request):

    def aa():
        print("aa--->")
        return 'I am aa'

    class Bar(object):

        def cc(self):
            print("Bar-->cc")

    B1 = Bar()
    return render(request, 'test.html', locals())
  • Template layer
{{ aa }}
{{ Bar }}
{{ B1 }}

image-20210318194502925

3. Notes on function name and class name

  • The transfer function name and class name are automatically called in parentheses
  • The result of passing in the function name is the return value of the function
  • Template syntax does not support additional parameters, that is, functions cannot pass parameters

4. Advantages and disadvantages of value transmission mode:

  • Value transfer mode 1: accurate value transfer, no waste of resources
  • Value transfer mode 2: simple value transfer may cause a certain waste of resources

4、 Getting values from template syntax

  • The syntax value of Django template can only use the period (.), that is, the dot

  • According to the index and key value, support many, many points

# views.py
def test_func(request):
    ll = [1,2,{"name":"shawn","age":23,"hobby":["read","study"]}]
    return render(request,"test.html",{"ll":ll})

#Want to read
# test.html
{{ ll.2.hobby.0 }}

image-20210318195629158

5、 Filter of template syntax

1. Filter description

  • Python like built-in methods
  • Pass the data on the left side of the vertical bar to the filter on the right as the first parameter
  • Grammar:{{[data] | filter: optional parameter}}
  • Note: there are no spaces on the left and right sides of the vertical bar
  • If the filter parameters contain spaces, they need to be wrapped in quotation marks
  • A filter can have at most two parameters

2. Use of common filters

  • There are about 60 filters in Django. The following only introduces the common filters
# views.py
def test_func(request):
    S = "Hello, big star!"
    i = 1314520
    f = 1.75
    l = [1,2,3,4,5]
    d = {"name":"shawn","age":23}
    t = (2,3,4,5,5)
    se = {3,4,5,'rr'}
    b = True
    w = 'aa bb cc dd ee ff'

    return render(request,'test.html',locals())
Statistical length: {{s | length}}

Addition operation: {I| add:1000  }}
String splicing: {{s | add: 'hello SpongeBob'}}
Splicing: {{s | join: '@'}}
Slice: {L | slice: '0:5:2'}}
Date format: {{CTime | date:'y-m-d H: I: s'}}

Default value: {{B | default: 'ha ha'}}  
File size: {file}_ size|filesizeformat }}
>
Intercepting text: {w | trun catechars:6  }}

Intercepted words: {w | trun catewords:3  }}

image-20210326223226444

3. Change your mind

  • Back end usage change
from django.utils.safestring import mark_safe
html_ safe = mark_ Safe ('Hello ')
  • Front end use change
{{ html|safe }}

6、 Label of template syntax

Similar to process control in Python

1. For loop

{% for i in l %}
    {{ forloop }}
    The {{I}} # loop takes elements from list L
{% endfor %}

Let’s seeforloopWhat is the output:

image-20210318214321276

2. If judgment

# i = 90

{% if i > 100 %}
    is True
{% elif i > 80 %}
    is two
{% else %}
    is no
{% endif %}

image-20210318215255704

3. Mixed use of for and if

{% for i in l %}
    {% if forloop.first %}
        is first
    {% elif forloop.last %}
        is last
    {% else %}
        {{ i }}
    {% endif %}
{% endfor %}

image-20210318215606748

4. Empty: empty

{% for foo in request %}
    {% empty %}
        The incoming data is empty and cannot be cycled
{% endfor %}

image-20210318215938511

5. With: take alias

{% with ll.2.hobby.0 as hb %}
    {{{HB}} can use alias values
    {{LL. 2. Hobby. 0}} # can also use the original way of value
{% endwith %}

image-20210318220320333

6. Dictionary values, keys and items methods

{% for k in d.keys %}
    {{ k }}
{% endfor %}

{% for v in d.values %}
    {{ v }}
{% endfor %}

{% for kv in d.items %}
    {{ kv }}
{% endfor %}

7、 Custom filter, label, inclusion_ tag

Similar to custom functions in Python

1. Create templatetags file

  • First, create a folder named “templatetags” under the application
  • Create a py file with any name under the change folder (example: mytag)
  • Write two lines of code in the PY file
from django import template
register = template.Library()

2. Custom filter

  • A custom filter can have at most two formal parameters
from .templatetags.mytag import register

#When importing a custom filter in the template layer, use the name specified here
@register.filter(name='myfilter')  
Def sums (a, b): # whatever the function name is
    Return a + B # returns the sum of two parameters
{% load mytag%} import tag file
{{ i| myfilter:100  }}Use myfilter filter

image-20210318225017009

3. Custom label

  • A custom label can have multiple parameters
from .templatetags.mytag import register

#When importing custom tags in the template layer, the name specified here is used
@register.simple_tag(name="my_tag")
def my_ Join (a, B, C, d): # function name is arbitrary
    Return f '{a} / {B} / {C} / {D}' #
{% load mytag%} import tag file
{% my_ Tag 'hello' pai 'Da' Xing '%} the parameters after the tag are separated by spaces

image-20210318230441986

  • Example 2
from .templatetags.mytag import register

#When importing custom tags in the template layer, the name specified here is used
@register.simple_tag(name="my_tag")
def my_ Join (a, b): # function name is arbitrary
    Return a + B # return sum
{% load mytag %}
{% my_tag i 100 %}

image-20210318231336629

4. Custom inclusion_ tag

  • inclusion_ The internal principle of tag:
  • Import the written inclusion in the HTML page_ Tag and call the
  • It triggers the execution of a function in the PY file and produces the result
  • The result is passed to an HTML page for rendering through template syntax
  • After rendering, call inclusion again_ Location of tag
  • Examples
from .templatetags.mytag import register

@register.inclusion_ tag('test.html',name='my_ incl_ The first parameter is the HTML page to render
def func(n):
    data=[]
    for i in range(n):
        Data. Append (f 'page {I})
    return locals()
#Test.html file
{% load mytag %}
{% my_incl_tag 6 %}
# test2.html
{{ data }}
{% for foo in data %}
    {% if forloop.first %}
        {{foo}}
    {% elif forloop.last %}
        {{ foo }}
    {% else %}
        {{ foo }}
    {% endif %}
{% endfor %}

The inclusion_ is called in the test.html page. Tag —– > triggers the execution of a function to generate the result and render it to the test2.html page. After rendering, it returns to the test.html page

image-20210318235133415

8、 Import of template

Similar to the back-end module, you can directly import what page you want

{% include 'edit. HTML'%} directly displays the contents of the edit. HTML file in the current HTML file

9、 Template inheritance

1. Use of template inheritance

  • Template inheritance first needs to select a template page, in which block is used to delimit the area that can be changed
#Motherboard page 'home. HTML' file
{% block [zone name]%}
......
{% endblock %}
  • Pages that you want to inherit can use extensions to inherit a page
#Sub Edition
{% extends 'home.html' %}
{% block [zone name]%}
......
{% endblock %}

The sub version inherits the template, so the overall format of the sub version is the same as the template, and the area divided by the block can be changed at will

2. Three areas of template

  • Motherboard in the division of the region when there are three areas
{% block css %}
    #CSS area
{% endblock %}

{% block content %}
    #HTML region
{% endblock %}

{% block js %}
    #JS area
{% endblock %}

The purpose is to make the sub version have independent CSS, JS and so on, and increase the scalability

  • The sub version can also continue to use the master to delimit the content within the area
{{ block.super }}

3. Examples

  • Routing layer
urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', views.func),
    path('index/', views.func2,name='index_name'),
]
  • View layer
def func(request):
    return render(request,'home.html')

def func2(request):
    return render(request,'index.html')
  • Template layer
# home.html
{% block left-body %}

    Hello, world!
    Here is an area divided by a block
    Learn more

{% endblock %}

# index.html
{% extends 'home.html' %}
{% block left-body %}
    
      
        
          
        
      
        
            
              
            
        
    
{% endblock %}
  • Home.html page

image-20210319153623274

  • Index.html page

image-20210319153709598

10、 Small exercises

1. Demand

  • Add, delete, modify and query functions

  • The function of adding, deleting, modifying and querying users is written by using template inheritance

  • The code is not much different from before except for the template layer

2. Code implementation

  • Urls.py file
from django.contrib import admin
from django.urls import path,re_path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', views.home_func,name='home_name'),
    re_path('^edit/(\d+)', views.edit_func,name='edit_name'),
    re_path('^del/(\d+)', views.del_func,name='del_name'),
    path('insert/', views.insert_func,name='insert_name'),
]
  • View.py file
def home_func(request):
    user_obj_list = models.User.objects.all()
    return render(request,'home.html',locals())

def edit_func(request,id):
    if request.method == "POST":
        name = request.POST.get('name')
        pwd = request.POST.get('pwd')
        age = request.POST.get('age')
        models.User.objects.filter(id=id).update(name=name,pwd=pwd,age=age)
        return redirect('home_name')
    user_obj = models.User.objects.filter(id=id).first()
    return render(request,'edit.html',{'user_obj':user_obj})

def del_func(request,id):
    models.User.objects.filter(id=id).delete()
    return redirect('home_name')

def insert_func(request):
    if request.method == "POST":
        name = request.POST.get('name')
        pwd = request.POST.get('pwd')
        age = request.POST.get('age')
        models.User.objects.create(name=name,pwd=pwd,age=age)
        return redirect('home_name')
    return render(request,'insert.html')
  • Template layer file
#Home.html file

##[navigation bar code]
##[left sidebar code]
##[content on the right is divided by block]
{% block left-body %}
    
        
            user data
            
                
                    
                    
                        number
                        full name
                        password
                        Age
                        operation
                    
                    
                    
                        {% for user_obj in user_obj_list %}
                            
                                {{ user_obj.id }}
                                {{ user_obj.name }}
                                {{ user_obj.pwd }}
                                {{ user_obj.age }}
                                
                                    delete
                                    modify
                                
                            
                        {% endfor %}
                    
                
            
                
                    
                
            
            
        
    
{% endblock %}


#Edit.html file

{% extends 'home.html' %}
{% block left-body %}


    modify数据
    
        
            username:
            
            password:
            
            age:
            
            
        
    


{% endblock %}


#Insert.html file

{% extends 'home.html' %}
{% block left-body %}
    
    
        insert data
        
            
            username:
                
            password:
                
            age:
                
                
            
        
    
    
{% endblock %}

image-20210319171604527

image-20210319171632069

image-20210319171716321

image-20210319171748532