1. 程式人生 > 其它 >django-模板中if標籤的應用

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>