templates模板
Filters过滤
add: 增加{{ 4 | add: "2" }} ==> 6
{{ [1,2,3] | add: [4,5,6] }} ==> [1,2,3,4,5,6]
addslashes: 增加反斜杠{{ "I'm using Django"| addslashes }} ==> "I'm using Django"
capfirst: 首字母大写center: 文字居中"{{ "Django"|center: "15" }} ==>
" Django "
cut: 去除指定字符date: 格式化时间{{ value|date:"D d M Y" }}
{{register_time|date:"o年m月d日"}}
default: 默认的值 {{ event.source|default:"未知来源" }}default_if_none: None才是defaultdictsort: 按照dict的某个key排序 {{ value|dictsort:"name" }}dictsortreversed: 逆序排列divisibleby: 能否被值整除length: 长度filesizeformat: 文件尺寸,自动从Byte变成 KB MBsafe 不进行转译
{{ var|safe }}[ ] safeseq
slice 切断一个列表
{{ some_list|slice:":2" }}
[ ] slugify
{{ value|slugify }}
Joel is a slug >>> joel-is-a-slug
[ ] stringformat
with:
{% with shor_name=longname.longsubname.longrealname %}
{% endwith %}
url 写法
{% url 'some-url-name' [v1 v2 arg1=v1 arg2=v2] %} # 这些参数必须直接放入
{% url 'some-url-name' [v1 v2 arg1=v1 arg2=v2] %}?id=3 # 额外的参数放后面
自定义标签
{% templatetag openvariable %} message {% templatetag closevariable %} # 临时输出个花括号标签
{% verbatim %}
{{if dying}}Still alive.{{/if}} # 这样中间的代码就不会进行渲染了。
{% endverbatim %}
Template API
Loading a Template
from django.template import Template
template = Template("My name is {{ my_name }}")
Rendering a context
from django.template import Context
context = Context({"my_name": "ramwni"})
template.render(context)