模板层-变量和标签
变量
可向模板中传递的类型:
str int list turple
dict func obj
在模板中变量的语法:
{{ 变量名 }}
{{ 变量名.index }} (按照索引取值)
{{ 变量名.key }} (传入的数据是一个字典,按键取值)
{{ 对象.方法 }}
{{ 函数名 }}
对象的方法及函数均不需要(),只写名称,可直接调用。
eg:
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<h3>int={{ int }}</h3>
<h3>str={{ str }}</h3>
<h3>list={{ list }}</h3>
<h3>list[1]={{ list.1 }}</h3>
<h3>dict={{ dict }}</h3>
<h3>dict['aa']={{ dict.aa }}</h3>
<h3>func={{ func }}</h3>
<h3>cat.cat_say={{ class_obj.cat_say }}</h3>
</body>
</html>
views:
def test_html(request):
t=loader.get_template('test_template.html')
class cat:
def cat_say(self):
return '喵喵喵'
def hello():
return 'hello'
data={
'int':1,
'str':'sdfsd',
'list':['a','b','c'],
'dict':{'aa':88,'bb':99},
'func':hello,
'class_obj':cat()
}
html=t.render(data)
return HttpResponse(html)
输出:
标签
{% 标签 %}
…
{% 结束标签 %}
if标签:
{% if 条件表达式1 %}
…
{% elif 条件表达式2 %}
.
.
.
{% else %}
…
{% endif %}
条件表达式基本同python,但不能用()
更多标签使用方法参考官方文档
联系:制作一个简单的网页计算器
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test_if</title>
</head>
<body>
<form action="/test_if" method="post">
<input type="text" name="x" value={{ x }} >
<select name="op">
<option value="add" {% if op == 'add' %}selected{% endif %} >+加</option>
<option value="sub" {% if op == 'sub' %}selected{% endif %} >-减</option>
<option value="mul" {% if op == 'mul' %}selected{% endif %} >*乘</option>
<option value="div" {% if op == 'div' %}selected{% endif %} >/除</option>
</select>
<input type="text" name="y" value={{ y }}>=<span>{{ result }}</span>
<div>
<input type="submit" value="开始计算">
</div>
</form>
</body>
</html>
视图函数:
def test_if(request:HttpRequest):
if request.method=='GET':
return render(request,'if_template.html')
else:
x=int(request.POST['x'])
op=request.POST['op']
y=int(request.POST['y'])
if op=='add':
result=x+y
elif op=='sub':
result=x-y
elif op=='mul':
result=x*y
else:
if y==0:
result='ERROR!'
else:
result=x/y
return render(request,'if_template.html',locals())
最终效果:
for标签
{% for 变量 in 可迭代对象 %}
循环语句
{% empty %}
可迭代对象为空时填充的语句
{% endfor %}
for标签内置变量:
forloop.counter 循环的当前迭代(从1开始)
forloop.counter() 循环的当前迭代(从0开始)
forloop.revcounter counter的倒序
forloop.revcounter() counter()的倒序
forloop.first 如果是第一次循环则为真
forloop.last 如果是最后一次循环则为真
forloop.parentloop 当嵌套循环,
eg:
views:
def test_for(request:HttpRequest):
mylist=['Tom', 'Bob', 'Timi']
return render(request,'for_template.html',locals())
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for i in mylist %}
<h3>第{{ forloop.counter }}个名字是{{ i }}</h3>
{% empty %}
<h3>无名字</h3>
{% endfor %}
</body>
</html>
结果: