
将服务器端的功能嵌入到模板中,流程控制……
标签语法:模板标签中引用变量不用再加双花括号
{% 标签 %}
……
{% 结束标签 %}
//if标签 运算符== != < > ……都能用,但括号优先级不能用
{% if 表达式 %}
……
{% elif 表达式 %}
……
{% endif %}
综合-计算器
使用模板和视图函数做一个计算器
视图函数
def scal(request):
# 拆分为GET和POST两种方法,如果是post方法才进行运算,与模板的action对应
if request.method == 'GET':
return render(request, 'scal.html')
elif request.method == 'POST':
x = int(request.POST['x'])
y = int(request.POST['y'])
op = str(request.POST['op'])
result = 0
if op == 'add':
result = x+y
elif op == 'sub':
result = x-y
elif op == 'mul':
result = x*y
elif op == 'div':
result = x/y
# locals 可以将函数体中各变量打包成字典
return render(request, 'scal.html', locals())
模板
计算器
微信扫一扫
支付宝扫一扫
评论列表(0条)