django-模板中if标签的应用

模板视图option标签+if判断

views

from django.http import  HttpResponse
from django.shortcuts import render

def mycal(request):
    if request.method=='POST':
        x=int(request.POST['x'])
        y=int(request.POST['y'])
        cal=request.POST['cal']
        if cal=='add':
            result=x+y
        
        elif cal=='sub':
            result=x-y
        elif cal=='mul':
            result=x*y
        elif cal=='div':
            result=x/y
        return  render(request,'test.html',locals())
    elif request.method=='GET':

        return render(request,'test.html')

url配置

from django.urls import path
from  . import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('mycal/',views.mycal)
]

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试页面计算</title>
</head>
<body>
    <form action= '/mycal/' method="POST">
        {% csrf_token %}
    <input type="text" name='x' value={{x}}>
    <select name="cal" >
        <option value="add" {% if cal == 'add' %} selected{% endif %}> +加</option>
        <option value="sup" {% if cal == 'sup' %} selected{% endif %}>-减</option>
        <option value="mul" {% if cal == 'mul' %} selected{% endif %}>*乘</option>
        <option value="div" {% if cal == 'div' %} selected{% endif %}>/除</option>



    </select>
    
    <input type="text" name="y" value={{y}}>
    =<span>{{result}}</span> 
    </br>
    <input type="submit" value='计算结果'>
    </form>
</body> 
</html>

网页内容显示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试页面计算</title>
</head>
<body>
    <form action= '/mycal/' method="POST">
        <input type="hidden" name="csrfmiddlewaretoken" value="24xDImyFe8BGhoPqSU1V5bhRtf9O5ERvq2y7QfdxnmEZH62tr0BuZss6PP4yjLPm">
    <input type="text" name='x' value=15>
    <select name="cal" >
        <option value="add" > +加</option>
        <option value="sup" >-减</option>
        <option value="mul" >*乘</option>
        <option value="div"  selected>/除</option>



    </select>
    
    <input type="text" name="y" value=20>
    =<span>0.75</span> 
    </br>
    <input type="submit" value='计算结果'>
    </form>
</body> 
</html>

if套用标签时:
{% if gname_option == "{{game.gname}}" %}

原文地址:https://www.cnblogs.com/yescarf/p/15087796.html