Analysis of python with tag usage

Time:2020-9-12

This article mainly introduces the use of python with tag parsing, the article through the example code is very detailed, for everyone’s study or work has a certain reference learning value, need friends can refer to

1. In Python DTL template, if you want to define variables, you can use the “with” statement.

2. There are two ways to use the “with” sentence

The first is the form of “with XX = XX”. Note that if you use this form to define variables, there must be no spaces on both sides of the = sign. Otherwise, the DTL template will not recognize it.

The second is the form of “with XXX as XXX”. In this form of with defining variables, the DTL template will automatically generate code fast format, which is relatively simple. Therefore, it is recommended to define DTL template variables in this form.

index.html The code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
{# use the with statement block to define a variable, and this variable can only be used in the statement block of the with variable. To be confused
  {% with books.1 as shz %}
    <p>{{ shz }}</p>
  {% endwith %}

Of course, you can use with in another way. To be confused
Note that if = is used, there should be no spaces on either side of the = sign. Otherwise, DTL will not recognize ා
  {% with xyj=books.3 %}
    <p>{{ xyj }}</p>
  {% endwith %}
</body>

views.py The code in the file is as follows:

from django.shortcuts import render
def index(request):
  context = {
    'books': [
      The romance of the Three Kingdoms,
      'outlaws of the marsh',
      'dream of Red Mansions',
      'journey to the West'
    ],
  }
  return render(request,'index01.html',context=context)

3. The variable defined can only be used in the with statement, but it cannot be retrieved when used outside the with statement block.

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.

Recommended Today

How to share queues with hypertools 2.5

Share queue with swote To realize asynchronous IO between processes, the general idea is to use redis queue. Based on the development of swote, the queue can also be realized through high-performance shared memory table. Copy the code from the HTTP tutorial on swoole’s official website, and configure four worker processes to simulate multiple producers […]