Python 10.4.1 Django framework: T.Django template

catalogue

1, Django uses its own template

1. Configuration

2. Define template

3. Template rendering

4. Template syntax

4.1 template variables

4.2 template statement

4.3 notes

5. Filter

5. Template inheritance

2, Django uses the jinja2 template

1. jinja2 introduction

2. Install jinja2 module

3. Django configuration jinja2

4. Most jinja2 templates are the same as Django's own templates

 5. jinja2 custom filter

1, Django uses its own template

1. Configuration

Create the template directory templates in the project.

In settings Modify DIRS value of TEMPLATES configuration item in py configuration file:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],  # Modify 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',
            ],
        },
    },
]

2. Define template

Create a new template file in the templates directory, such as index html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ city }}
</body>
</html>

3. Template rendering

There are two steps to call a template:

  1. Find template loader get_ Template (relative path of template file in template directory) - > return template object

  2. Render template objects Render (context = None, request = None) - > returns the rendered html text string. Context is the template variable dictionary, and the default value is None. Request is the request object, and the default value is None

For example, define a view

from django.http import HttpResponse
from django.template import loader

def index(request):
    # 1. Get template
    template=loader.get_template('index.html')

    context={'city': 'Beijing'}
    # 2. Rendering template
    return HttpResponse(template.render(context))

Django provides a function render, which can abbreviate the above code.

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)

4. Template syntax

4.1 template variables

Variable names must consist of letters, numbers, underscores (not beginning with an underscore) and dots.

The syntax is as follows:

{{variable}}

Template variables can be built-in types of python or objects.

def index(request):
    context = {
        'city': 'Beijing',
        'adict': {
            'name': 'Journey to the West',
            'author': 'Wu Chengen'
        },
        'alist': [1, 2, 3, 4, 5]
    }
    return render(request, 'index.html', context)

4.2 template statement

1) for loop:

  

2) if condition:

 

The comparison operators are as follows:

==
!=
<
>
<=
>=

Boolean operators are as follows:

and
or
not

Note: the left and right sides of the operator cannot be next to variables or constants, and there must be spaces.

{% if a == 1 %}  # correct
{% if a==1 %}  # error

4.3 notes

1) The syntax of a single line comment is as follows:

{#...#}

2) Multi line comments use the comment tag. The syntax is as follows:

{# comment #}
...
{# endcomment #}

5. Filter

The syntax is as follows:

  • Use the pipe symbol | to apply filters for calculation and conversion operations, which can be used in variables and labels.
  • If the filter requires parameters, use colon: to pass the parameters.
  • variable|filter:parameter
    

Several are listed as follows:

  • Safe, disable escape, tell the template that this variable is safe and can explain the execution

  • Length, length, returns the number of characters contained in a string, or the number of elements in a list, tuple, or dictionary.

  • Default, the default value. If the variable does not exist, the default value is returned.

  • data|default:'Default value'
    
  • Date, date, used to format the string of date type values. The common formatting characters are as follows:

    • Y represents the year in 4-digit format, and Y represents the two digit year.
    • m represents month, in the format of 01, 02, 12, etc.
    • d represents day, in the format of 01, 02, etc.
    • j represents day, in the format of 1, 2, etc.
    • H represents the hour in hexadecimal 24, and H represents the hour in hexadecimal 12.
    • i represents score, 0-59.
    • s represents seconds, 0-59.
    • value|date:"Y year m month j day  H Time i branch s second"

5. Template inheritance

Template inheritance and class inheritance have the same meaning, mainly to improve code reuse and reduce the workload of developers.

Parent template

If you find that some content is the same in multiple templates, you should define this content in the parent template.

Tag block: used to reserve an area in the parent template for the child template to fill in different content. The name cannot be the same. For better readability, it is recommended to write a name on the endblock tag, which is the same as the corresponding block name. The data passed from the context can also be used in the parent template.

Sub template

Label extends: inheritance, written in the first line of the sub template file.

 {% block name %}

In the reserved area, you can write default content or no default content

 {% endblock name %}

The child template does not need to fill all reserved areas in the parent template. If the child template is not filled, the default value defined by the parent template is used.

 {% extends "Parent template path" %}

Fills the reserved area with the name specified in the parent template.

{% block name %}

Actual fill content

{{ block.super }}

Used to get the information in the parent template block Content of

 {% endblock name %}

 

2, Django uses the jinja2 template

1. jinja2 introduction

Jinja2: it is the next widely used template engine in Python. It is a template language implemented by python. Its design idea comes from Django's template engine and extends its syntax and a series of powerful functions, especially the built-in template language in Flask framework

Because Django's default template engine is not fully functional and slow, we can also use jinja2 in Django. Jinja2 claims to be 10-20 times faster than Django's default template engine.

Django's mainstream third-party apps basically support Django's default template and jinja2 at the same time, so there won't be many obstacles to using jinja2.

2. Install jinja2 module

    pip install jinja2

3. Django configuration jinja2

1. Create jinja2 in the project file_ env. Py file

from jinja2 import Environment

def environment(**options):
    env = Environment(**options)

    return env

2. In settings Py file

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',#Amendment 1
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS':True,
        'OPTIONS':{
            'environment': 'jinja2_env.environment',# Revision 2
            'context_processors':[
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

4. Most jinja2 templates are the same as Django's own templates

 5. jinja2 custom filter

Django documentation

In jinja2_ env. Custom filters in py files

from jinja2 import Environment

def environment(**options):
    env = Environment(**options)

    # 2. Add a custom filter to the environment
    env.filters['do_listreverse'] = do_listreverse

    return env

# 1. Custom filter
def do_listreverse(li):
    if li == "B":
        return "ha-ha"

 

Keywords: Python Django Middleware

Added by desithugg on Wed, 29 Dec 2021 23:51:34 +0200