首页 > 编程语言 > 详细

Python - Django - 模板语言之 Tags(标签)

时间:2019-07-26 23:35:39      阅读:98      评论:0      收藏:0      [点我收藏+]

标签使用 {% %}

注释语句:{# #}

for 循环:

views.py:

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


# Filter 测试
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 测试</title>
</head>
<body>

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

</body>
</html>

运行结果:

技术分享图片

for 循环的其它使用方式:

forloop.counter 当前循环的索引值,从 1 开始
forloop.counter0 当前循环的索引值,从 0 开始
forloop.revcounter 当前循环的倒序索引值,从 1 开始
forloop.revcounter0 当前循环的倒序索引值,从 0 开始
forloop.first 当前循环是不是第一次循环,结果为布尔值
forloop.last 当前循环是不是最后一次循环,结果为布尔值
forloop.parentloop 本层循环的外层循环

 

 

 

 

 

empty:

如果内容为空的话,就执行,配合 for 循环使用

views.py:

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


# Filter 测试
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 测试</title>
</head>
<body>

{% for hobby in hobby_list %}
    {{ hobby }}
{% empty %}
    <li>没有东西</li>
{% endfor %}

</body>
</html>

运行结果:

技术分享图片

if 语句:

if 语句支持 ==、>、<、!=、<=、>=、and、or、in、not in、is、is not 判断

views.py:

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


# Filter 测试
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 测试</title>
</head>
<body>

{% if hobby_list|length != 5 %}
    <p>列表长度不等于 5</p>
{% else %}
    <p>列表长度等于 5</p>
{% endif %}

</body>
</html>

运行结果:

技术分享图片

with 语句:

用来定义一个中间变量,多用于给一个复杂的变量起别名

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

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

<!-- 或者 -->

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

</body>
</html>

运行结果:

技术分享图片

注意:“=” 两边不能加空格

Python - Django - 模板语言之 Tags(标签)

原文:https://www.cnblogs.com/sch01ar/p/11253019.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!