Django模板语法
模板变量
变量名必须由字母、数字、下划线(不能以下划线开头)和点组成。
语法如下:
{{变量}}
模板变量可以使python的内建类型,也可以是对象。
def index(request): context = { 'city': '北京', 'adict': { 'name': '西游记', 'author': '吴承恩' }, 'alist': [1, 2, 3, 4, 5] } return render(request, 'index.html', context) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>{{ city }}</h1> <h1>{{ adict }}</h1> <h1>{{ adict.name }}</h1> 注意字典的取值方法 <h1>{{ alist }}</h1> <h1>{{ alist.0 }}</h1> 注意列表的取值方法 </body> </html>
模板语句
1)for循环:
{% for item in 列表 %}
循环逻辑
{{forloop.counter}}表示当前是第几次循环,从1开始
{%empty%} 列表为空或不存在时执行此逻辑
{% endfor %}
2)if条件:
{% if ... %}
逻辑1
{% elif ... %}
逻辑2
{% else %}
逻辑3
{% endif %}
比较运算符如下:
==
!=
<
>
<=
>=
布尔运算符如下:
and
or
not
注意:运算符左右两侧不能紧挨变量或常量,必须有空格。
{% if a == 1 %} # 正确
{% if a==1 %} # 错误

浙公网安备 33010602011771号