Django's template system

First, the composition of the template

html code and logic control code

Second, the form of logic control code

1. Variables (use double curly brackets to refer to variables)

a、template和context

Syntax: {{ var_name }}

The template system can not only pass strings, it can pass arbitrary objects. For objects such as lists, dictionaries, and tuples, we can use periods to process them, which is called deep variable search

eg

Corresponding to views.py

def index(request):
    l = [1, 2, 3]
    return render(request, 'index.html', locals())

 Corresponding to index.html

< body > 
< h1 > The first element of the passed list is {{ l.0 }} </ h1 > 
</ body >

browser back

The first element of the passed list is 1

b, variable filter filter

Syntax: {{ object | filter: parameter}}

There are add, addslashes, capfirst, cut, date, default, default_if_none, etc. in the filter

add: add the corresponding value to the variable

addslashes: add slashes before quotes in variables

capfirst: capitalize the first letter

cut: remove specified characters

date: formatted time

。。。

If the incoming variable is a label and you want to implement its function, you should use the safe function

eg:

no safe function

< body > 
< h1 > The first element of the passed list is {{ l.0 }} </ h1 >
This is a {{ s }}
</body> 

browser output

This is a <a href='#'> jump link </a> _ _ 

Use safe functions

< body > 
< h1 > The first element of the passed list is {{ l.0 }} </ h1 >
This is a {{ s|safe }}
</body>

browser output

This is a jump link

autoescape can also achieve the same function

eg

< body > 
< h1 > The first element of the passed list is {{ l.0 }} </ h1 > 
This is a {{ s|safe }} < br >
{% autoescape off%}
    This is a {{ s }}
{% endautoescape %}
</body>

  2. The use of tags (using a combination of braces and percentages to indicate the use of tags)

Syntax: {% tag %}

a. The use of {% if %}, to make judgments, if there is an if, there must be {% endif %}

eg:

{% if l.0 > 3 %}
    <h2>
    {{ l.0 }}
    {% else %}
        <h2>
    {{ l.2 }}
{% endif %}
</h2> 

b. The use of {% for %}, for traversal, if there is a for, there must be {% endfor %}

eg:

{% for num in l %}
    <p>{{ num }}</p>
{% endfor %} 

There is also a forloop template variable built into the for loop. Forloop.counter represents the number of loops, it starts counting from 1, the first loop is set to 1, forloop.counter0 starts counting from 0, forloop.revcounter reverses the count, forloop. The value of first is True the first time it loops

eg:

{% for num in l %}
    <p>{{ forloop.counter0 }}:{{ num }}</p>
    <p>{{ forloop.counter }}:{{ num }}</p>
{% endfor %}

c. {%csrf_token%}: csrf_token label

When the form is submitted by the post method, django will report an error, which is a protection mechanism of django to prevent cross-site attacks

eg:

<form action="/blog/register/" method="post">
    姓名<input type="text" name="username"><br>
    密码<input type="text" name="psw"><br>
    <input type="submit">
</form>

error message

Forbidden (403)

CSRF verification failed. Request aborted.

You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.

If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests.

Submit successfully after adding

<form action="/blog/register/" method="post">
    姓名<input type="text" name="username"><br>
    密码<input type="text" name="psw"><br>
    <input type="submit">
    {% csrf_token %}
</form>

 d. {% url %} refers to the address of the routing configuration

eg:

<form action="{% url 'reg' %}" method="post">
    姓名<input type="text" name="username"><br>
    密码<input type="text" name="psw"><br>
    <input type="submit">
    {% csrf_token %}
</form>

req is the alias in the routing configuration 

e. {% verbatim %}: Render is prohibited, there is an end at the beginning {% endverbatim %}

The code contained in it will not be rendered by the render

f, {% load %}: load tag library

g, {% with %}: replace complex variable names with simpler variable names, requires {% endwith %}

eg:

{% with s=qwer %}
    {{ s }}
{% endwith %}

Note: There must be no space between s=qwer, otherwise an error will be reported


 3. Custom filter and simple_tag

a. Create the templatetags module in the app (required)

b. Create any .py file, such as: mytag.py

eg:

customize

from django import template
from django.utils.safestring import mark_safe


register = template.Library()#The variable name must be registered


@register.filter
def filter_mul(a, b):
    return a*b


@register.simple_tag()
def tag_mul(a, b):
    return a*b

 

how to use

Load {% load mytag %} in the first line of the html file, the file created here is mytag.py

eg:

{% load mytag %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>BBU</title>
</head>

 

It should be noted that filter can be used after statements such as if, simple_tag cannot

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325304873&siteId=291194637