26.python中if标签的使用详解

if标签:if标签相当于Python中的if语句,有elif和else相对应,但是所有的标签需要用标签符号{% %}进行包裹。if标签可以使用==,!=,=<,>=,in,not in, is, is not等判断运算符,示例代码如下:

views.py文件中:
from django.shortcuts import render


def index(request):
    context = {
        'age':20
    }
    return render(request,'index.html',context=context)
urls.py文件中
from django.urls import path
from . import views

urlpatterns = [
    path('',views.index,name = 'index')
]
index.html文件中:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% if age <= 18 %}
        <p>您还没有满18岁,不能进入网吧</p>
    {% elif age == 18 %}
        <p>您已经18岁了,可以进入网吧了</p>
    {% else %}
        <p>您已经是成年人了,可以工作了哦。</p>
    {% endif %}
</body>
</html>

在模板中,使用if…in…标签进行遍历列表,示例代码如下:

views.py文件中:
from django.shortcuts import render


def index(request):
    context = {
        'heros':[
            '鲁班',
            '阿珂',
            '李白',
            '程咬金'
        ],
    }
    return render(request,'index.html',context=context)
index.html中:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% if "鲁班" in heros %}
        <p>鲁班正在待命</p>
    {% else %}
        <p>鲁班正在睡觉啊,则可怎么办呀?</p>
    {% endif %}
</body>
</html>
发布了76 篇原创文章 · 获赞 2 · 访问量 2754

猜你喜欢

转载自blog.csdn.net/zjy123078_zjy/article/details/103996061
今日推荐