1、模板继承
{% extends "base.html" %}
2、判断
{% firstof var1 var2 var3 %}
等价于
{% if var1 %}
{{ var1 }}
{% elif var2 %}
{{ var2 }}
{% elif var3 %}
{{ var3 }}
{% endif %}
3、循环
{% for athlete in athlete_list %}
{{ athlete.name }}
{% endfor %}
4、翻转列表
{% for obj in list reversed %}.
5、元素是元组的列表循环
{% for x, y in points %}
There is a point at {{ x }},{{ y }}
{% endfor %}
6、字典循环
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}
7、循环参数
变量说明forloop.counter顺序迭代序号 (1-开始)forloop.counter0顺序迭代序号 (0-开始)forloop.revcounter逆序迭代序号 (1-开始)forloop.revcounter0逆序迭代序号 (0-开始)forloop.first循环第一次经过forloop.last循环最后一次经过forloop.parentloop嵌套循环,父循环8、空序列判断 for … empty
{% for athlete in athlete_list %}
{{ athlete.name }}
{% empty %}
Sorry, no athletes in this list.
{% endfor %}
等价于
{% if athlete_list %}
{% for athlete in athlete_list %}
{{ athlete.name }}
{% endfor %}
{% else %}
Sorry, no athletes in this list.
{% endif %}
9、条件判断 if
{% if athlete_list %}
Number of athletes: {{ athlete_list|length }}
{% elif athlete_in_locker_room_list %}
Athletes should be out of the locker room soon!
{% else %}
No athletes.
{% endif %}
10、布尔操作 and, or or not
{% if athlete_list and coach_list or cheerleader_list %}
11、条件判断 ==, !=, , =, in, not in, is, and is not
{% if somevar == "x" %}
This appears if variable somevar equals the string "x"
{% endif %}
12、模板包含
{% include "foo/bar.html" %}
13、时间
It is {% now "jS F Y H:i" %}
{{ value|date:"D d M Y" }} # 日期格式化
{{ value|time:"H:i" }} # 时间格式化
datetime |date:"Y-m-d H:i:s" # 年-月-日 时:分:秒
14、模板标签
ArgumentOutputsopenblock{%closeblock%}openvariable{{closevariable}}openbrace{closebrace}opencomment{#closecomment#}15、函数
{{ value|add:"2" }} # 加法
{{ value|capfirst }} # 首字母大写
{{ value|title }} # 句子单词首字母大写
{{ value|center:"15" }} # 文字居中,剩余填充
{{ value|ljust:"10" }} # 文字左对齐,剩余填充
{{ value|rjust:"10" }} # 文字右对齐,剩余填充
{{ value|cut:" " }} # 移除空白
{{ value|default:"nothing" }} # 空值默认
{{ value|default_if_none:"nothing" }} # None值默认
{{ value|dictsort:"name" }} # 字典排序
{{ value|filesizeformat }} # 文件大小格式化
{{ value|first }} # 序列的第一个值
{{ value|last }} # 序列最后一个值
{{ value|floatformat:3 }} # 浮点值精度
{{ value|join:" // " }} # 序列拼接
{{ value|make_list }} # 字符串转列表
{{ value|length }} # 序列长度
{{ value|length_is:"4" }} # 长度判断
{{ value|lower }} # 字符串转小写
{{ value|upper }} # 字符串转小写
{{ value|random }} # 序列中随机取值
{{ some_list|slice:":2" }} # 切片
{{ value|striptags }} # 去除标签
{{ value|truncatechars:9 }} # 控制输出字符长度,超出省略号
{{ value|truncatewords:2 }} # 控制输出单词长度,超出省略号
{{ value|wordcount }} # 统计字数
参考: Built-in template tags and filters 时间格式化参考: https://docs.djangoproject.com/zh-hans/2.0/ref/templates/builtins/#date