Using Python in with tags Detailed

1. In the python DTL template, you want to define a variable, can be achieved by "with" statement.

2. "with" statement is used in two ways:

The first is a form of "with xx = xx", and noted that the use of this form define variables, no spaces around the = sign, otherwise, DTL template would not identify.
The second is in the form of "with xxx as xxx" is. This variable is defined with the form, DTL template automatically generates code format fast, relatively speaking, it is relatively simple. It is recommended to use template variables defined DTL in this form.

index.html code as follows:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{# 使用with语句块定义变量,并且这个变量只能在with变量的语句块中使用。 #}
    {% with books.1 as shz %}
        <p>{{ shz }}</p>
    {% endwith %}

{# 当然也可以使用另外一种方式使用with。 #}
{# 注意,如果使用=的话,=号两边不能有空格,否者的话,DTL会识别不了#}
    {% with xyj=books.3 %}
        <p>{{ xyj }}</p>
    {% endwith %}
</body>
views.py file code is as follows:
from django.shortcuts import render


def index(request):
    context = {
       'books': [
           '三国演义',
           '水浒传',
           '红楼梦',
           '西游记'
       ],
    }
    return render(request,'index01.html',context=context)

3. Define the variables can only be used with statement, a variable can not take on the outside with a block of statements.

Guess you like

Origin www.cnblogs.com/guyan-2020/p/12199071.html