Django template layer


Django template layer

The folder corresponding to the template layer is templates, which is used to store HTML files.

The back end sends the data to the front end through code, and the front end displays the data to the HTML page through template syntax.


1、 The back end transmits data to the front end

There are two value transfer methods:

① Pass by name (only those needed)

② Pass it all at once (local method, do you need to pass it all)

def show_data(request):
    str1 = 'hello'
    int1 = 17
    dict1 = {'name': 'tom', 'age': 21}
    list1 = [1, 2, 3, 4, 5]
    tuple1 = (6, 7, 8, 9, 10)
    set1 = {'a', 'b', 'c', 'd', 'e'}
    bool1 = True
    float1 = 12154.54
    "" "the first method: pass by name (only the required ones)" ""
    return render(request, 'show_data.html', {'str1': str1,
                                              'int1': int1,
                                              'dict1': dict1,
                                              'list1': list1,
                                              'tuple1': tuple1,
                                              'set1': set1,
                                              'bool1': bool1,
                                              'float1': float1
    "" "the second method of value transfer: the locals () method, which transfers all values at one time (whether it is necessary or not)" ""
    # return render(request, 'show_data.html', locals())



Two. Template syntax

1. Template syntax comments

{# template syntax comments #}


2. Template syntax value {}}

There is only one operation mode for Django template syntax to get container type (list, tuple, dict, set) data     Period

Front end code

Django template layerDjango template layer

Syntax value of front-end template
String value
{{ str1 }}
Integer value
{{ int1 }}
Dictionary value
{{ dict1 }}
{{dict1. Name} // the value of the period character is obtained by the property name
{{ dict1.age }}
List value
{{ list1 }}
{{list1.0} // the value of the period character is obtained through the index
{{ list1.1 }}
{{ list1.2 }}
{{ list1.3 }}
{{ list1.4 }}
Tuple value
{{ tuple1 }}
{{tuple1.0} // the value of the period character is obtained through the index
{{ tuple1.1 }}
{{ tuple1.2 }}
{{ tuple1.3 }}
{{ tuple1.4 }}
Set value
{{ set1 }}
Boolean value
{{ bool1 }}
Floating point value
{{ float1 }}

Template syntax value front end code


3. Template syntax filter

filter   | The one on the left will be the first parameter of the filter, and the one on the right of the filter will be the second parameter


①  | Length calculated length

{{str1|length} # find the length of STR1


② |add addition operation can be used for both digital addition and string splicing. If it cannot be added, it returns null

{{INT1 | add: 10} # add INT1 to 10


③ Default determines whether it is empty

{{a | default: ‘I am the default’}} # judge whether a is empty. If it is not empty, return A. if it is empty, return the following ‘I am the default’


④ |truncatechars: three dots count how many characters a number intercepts

{{STR1: truncatechars: 2} # intercept two characters


⑤ |truncatewords: how many words are intercepted by numbers? Three points do not count (intercepted according to the space)

{{STR2: truncatewords: 5} # intercept 5 words


⑥ Slice slice operation

{{str3 | slice: ‘0:8:2’}} # cut 0-8 characters of str3 in steps of 2


⑦ |date conversion date

{{time1 | date: ‘Y / M / D’}}


⑧ |filesizeformat gets the file size

{{ file_ Size|filesizeformat} # calculation file_ Size of size


4. Template syntax escape

|Safe escape


The front-end code does not have to be written at the front-end, but can be rendered at the front-end after the back-end code is written


Backend code:

def show_data(request):
    res = 'hello python world'
    return render(request, 'show_data.html', {'res': res})

Front end code:

{{ res|safe }}

design sketch:

Summary: the front-end code does not have to be written on the front-end page. It can be written in the mouth and passed to the front-end page for use. In this way, more logical syntax can be used on the back-end


5. Label of template syntax (logically related)

1) For loop syntax (input for at the front end and press tab to complete automatically)

{% for foo in list1 %}
    {{ foo }}
{% endfor %}

{% for foo in list1 %}
    {{ forloop }}
{% endfor %}

{% for foo in list1 %}
    {% if forloop.first %}
        This is the first time to print out {{foo}}
    {% elif forloop.last %}
        This is the last time, print out {{foo}}
    {% else %}
        {{ foo }}
    {% endif %}
        After printing {{foo}}, I will be printed
{% endfor %}

2) When the steps of obtaining a value are very cumbersome, but need to be used in many places, we can use the alias to simplify the code (the alias can only be used in with)

Backend code:

def show_data(request):
    dict1 = {'account': ['tom', {'username': ['tank', 'jack']}]}
    return render(request, 'show_data.html', {'dict1': dict1})

Front end code:

{% with dict1.account.1.username.1 as name %}
        {{ dict1.account.1.username.1 }}
        {{ name }}
{% endwith %}

design sketch:


6. Custom filters, labels, inclusion_ tag

Preliminary preparations:

①   Create a new folder under the application name. The name must be templatetags

②   Create a new py file with any name in this folder

③   The following two sentences of code must be written in this file

from django.template import Library
Register = library() # generates a library object

1) Custom filter (only two parameters can be passed)

Templatetags \ backend

from django.template import Library

register = Library()

#Custom filter
def num(a, b):
    return a+b

show_ Data.html front end display page

{% load mytags %}
{{ 10|def_sum:20 }}

2) . use of user-defined labels (multiple parameters can be passed)

Templatetags \ backend

#Custom label
def xxx(a, b, c, d):
    return '%s-%s-%s-%s' % (a, b, c, d)

show_ Data.html front end display page

{% load mytags %}
{%  link_str 1 2 3 'hello' %}

Note: custom filters can be used in logical statements, but custom labels cannot

3) . user defined inclusion_ tag

Templatetags \ backend

#Custom inclusion_ tag
@register.inclusion_tag('demo2.html', name='def_inclusion')
def demo(n):
    list1 = []
    for i in range(n):
    return locals()

demo2.html     ( inclusion_ Tag first places the value passed from the back-end code in the third-party HTML page demo.html, and then presents the content of the demo.html page in the index.html front-end display page)

{% for foo in list1 %}
    {{ foo }}
{% endfor %}

show_ Data.html front end display page

{% load mytags %}
{% def_inclusion 5 %}



Three. Template inheritance

If most areas of a page are public, this page can be used as a template page. When others inherit this page, they can only modify the corresponding area code to reduce the amount of code

The template page delimits the area through block.


1. Master page code

{# write the public page code #}
{% block content %}
{# write modifiable HTML code #}
{% endblock %}
{# write the public page code #}


2. Sub page inheritance

①   Import the whole template in the sub page first (you don’t need any code in the sub page, you can import it directly)

{% extensions' template main page. HTML '%}

②   Modify a specific area by implementing the planned area name

{% block content %}
#Write the sub page's own HTML code content
{% endblock %}


3. Template inheritance specification

Typically, the template page should have at least three areas

{% block css %}
{# main page CSS code #}
{% endblock %}

{% block content %}
{# main page content code #}
{% endblock %}

{% block js %}
{# main page JS code #}
{% endblock %}

It also supports the child page to call the content of the corresponding area of the parent page (template page), and can be called infinitely

{{ block.super }}



4、 Import of template

Each front-end page component written in advance (navigation bar, pager, label bar, etc.) can be placed in an HTML file separately (this HTML page is usually not a complete page, but a local style) as a page component template, which can be imported into other HTML pages for easy use.

Import method:

{% include 'page component template. HTML'%}

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]