Python - Django - Tags for Template Language

Keywords: PHP Django

Label use {%}

Annotation statement: {#}

for loop:

views.py:

from django.shortcuts import render, redirect, HttpResponse
from app01 import models


# Filter test
def filter_test(request):
    hobby = ["Reading", "Basketball", "Movie", "Music"]
    return render(request, "filter_test.html", {"hobby_list": hobby,})

filter_test.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Filter test</title>
</head>
<body>

{% for hobby in hobby_list %}
    {{ hobby }}
{% endfor %}

</body>
</html>

Operation results:

Other uses of the for cycle:

forloop.counter The index value of the current loop, starting from 1
forloop.counter0 Index values for the current loop, starting at 0
forloop.revcounter The inverted index value of the current loop, starting from 1
forloop.revcounter0 The inverted index value of the current loop, starting at 0
forloop.first Is the current loop the first, resulting in Boolean values?
forloop.last Is the current loop the last, resulting in a Boolean value
forloop.parentloop The outer cycle of the underlying cycle

 

 

 

 

 

empty:

If the content is empty, it is executed with for recycling

views.py:

from django.shortcuts import render, redirect, HttpResponse
from app01 import models


# Filter test
def filter_test(request):
    hobby = []
    return render(request, "filter_test.html", {"hobby_list": hobby,})

filter_test.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Filter test</title>
</head>
<body>

{% for hobby in hobby_list %}
    {{ hobby }}
{% empty %}
    <li>Nothing at all</li>
{% endfor %}

</body>
</html>

Operation results:

if statement:

if statement support==,>,<,!=,<=,>=, and, or, in, not, is, is not judgement

views.py:

from django.shortcuts import render, redirect, HttpResponse
from app01 import models


# Filter test
def filter_test(request):
    hobby = ["Reading", "Basketball", "Movie", "Music"]
    return render(request, "filter_test.html", {"hobby_list": hobby,})

filter_test.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Filter test</title>
</head>
<body>

{% if hobby_list|length != 5 %}
    <p>List length is not equal to 5</p>
{% else %}
    <p>List length equals 5</p>
{% endif %}

</body>
</html>

Operation results:

with statement:

Used to define an intermediate variable, often to alias a complex variable.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Filter test</title>
</head>
<body>

{% with a=hobby_list.1 %}
    {{ a }}
{% endwith %}

<!-- perhaps -->

{% with hobby_list.0 as b %}
    {{ b }}
{% endwith %}

</body>
</html>

Operation results:

Note: No spaces can be added on either side of "="

Posted by wxflint on Mon, 14 Oct 2019 09:22:07 -0700