Django模板中只需要记两种特殊符号:
{{ }}和 {% %}
{{ }}表示变量,在模板渲染的时候替换成值,{% %}表示逻辑相关的操作。
{{ 变量名 }}
变量名由字母数字和下划线组成。
点(.)在模板语言中有特殊的含义,用来获取对象的相应属性值。
几个例子:
view中代码:
def template_test(request):
l = [11, 22, 33]
d = {"name": "asd"}
class Person(object):
def \_\_init\_\_(self, name, age):
self.name = name
self.age = age
def dream(self):
return "{} is dream...".format(self.name)
asd = Person(name="asd", age=34)
qwe = Person(name="qwe", age=9000)
zxc = Person(name="zxc", age=18)
person\_list = \[asd, qwe, zxc\]
return render(request, "template\_test.html", {"l": l, "d": d, "person\_list": person\_list})
模板中支持的写法:
{# 取l中的第一个参数 #}
{{ l.0 }}
{# 取字典中key的值 #}
{{ d.name }}
{# 取对象的name属性 #}
{{ person_list.0.name }}
{# .操作只能调用不带参数的方法 #}
{{ person_list.0.dream }}
注:当模板系统遇到一个(.)时,会按照如下的顺序去查询:
翻译为过滤器,用来修改变量的显示结果。
语法: {{ value|filter_name:参数 }}
'|'左右没有空格没有空格没有空格
default
{{ value|default:"nothing"}}
如果value值没传的话就显示nothing
注:TEMPLATES的OPTIONS可以增加一个选项:string_if_invalid:'找不到',可以替代default的的作用。
filesizeformat
将值格式化为一个 “人类可读的” 文件尺寸 ,以字节为单位(例如 '13 KB', '4.1 MB', '102 bytes', 等等)。例如:
{{ value|filesizeformat }}
如果 value 是 123456789,输出将会是 117.7 MB。
add
给变量加参数
{{ value|add:"2" }}
value是数字4,则输出结果为6。
{{ first|add:second }}
如果first是 [1,.2,3] ,second是 [4,5,6] ,那输出结果是 [1,2,3,4,5,6] 。
lower
小写
{{ value|lower }}
upper
大写
{{ value|upper}}
title
标题
{{ value|title }}
ljust
左对齐
"{{ value|ljust:"10" }}"
rjust
右对齐
"{{ value|rjust:"10" }}"
center
居中
"{{ value|center:"15" }}"
length
{{ value|length }}
返回value的长度,如 value=['a', 'b', 'c', 'd']的话,就显示4.
slice
切片
{{value|slice:"2:-1"}}
first
取第一个元素
{{ value|first }}
last
取最后一个元素
{{ value|last }}
join
使用字符串拼接列表。同python的str.join(list)。
{{ value|join:" // " }}
truncatechars
如果字符串字符多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列(“…”)结尾。
参数:截断的字符数
{{ value|truncatechars:9}}
date
日期格式化
1.在函数中更改(方法一)
date_now = datetime.datetime.now() # 默认格式Sept. 10, 2018, 4:05 p.m.
date_now=date_now.strftime('%Y-%m-%d %H:%M:%S') # 改变默认方式
2.在setting中写(方法二)
函数中这么写
import datetime
date_now = datetime.datetime.now() # 默认格式Sept. 10, 2018, 4:05 p.m.
设置中这么写
在html中这么写
{{ value|date:"Y-m-d H:i:s"}}
{{ date_now|date:"H:i:s" }} # 19:40:00 设置后还可以进行过滤,改变格式
可格式化输出的字符:点击查看:https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#date
safe
Django的模板中会对HTML标签和JS等语法标签进行自动转义,原因显而易见,这样是为了安全。但是有的时候我们可能不希望这些HTML元素被转义,比如我们做一个内容管理系统,后台添加的文章中是经过修饰的,这些修饰可能是通过一个类似于FCKeditor编辑加注了HTML修饰符的文本,如果自动转义的话显示的就是保护HTML标签的源文件。为了在Django中关闭HTML的自动转义有两种方式,如果是一个单独的变量我们可以通过过滤器“|safe”的方式告诉Django这段代码是安全的不必转义。
比如:
view:
value = "点我"
'js'= """"""
html:
{{ value|safe}}
{{js|safe}}
自定义过滤器只是带有一个或两个参数的Python函数:
例如,在过滤器{{var | foo:“bar”}}中,过滤器foo将传递变量var和参数“bar”。
自定义filter代码文件摆放位置:
app01/
__init__.py
models.py
templatetags/ # 在app01下面新建一个 templatetags(包),这个名字不能变
__init__.py
myfilters.py # 建一个存放自定义filter的py文件
views.py
编写自定义filter
from django import template
register=template.Library()
@register.filter
def add_sb(value,arg='very'): #arg='very'默认参数
return "{}_{}_sb".format(value,arg)
@register.filter(name='dsb') #dsb等同于add_dsb
def add_dsb(value,arg="**"):
return "{}_{}_dsb".format(value,arg)
使用自定义filter
{# 先导入我们自定义filter那个文件 #}
{% load myfilters %}
{# 使用我们自定义的filter #}
{{ name_list.1|add_sb:"非常" }}
{{ name_list.0|add_sb}}
{{ name_list.3|dsb}}
Tags
for
for循环可用的一些参数:
Variable
Description
forloop.counter
当前循环的索引值(从1开始)
forloop.counter0
当前循环的索引值(从0开始)
forloop.revcounter
当前循环的倒序索引值(从1开始)
forloop.revcounter0
当前循环的倒序索引值(从0开始)
forloop.first
当前循环是不是第一次循环(布尔值)
forloop.last
当前循环是不是最后一次循环(布尔值)
forloop.parentloop
本层循环的外层循环
forloop的本质是字典
在forloop中自由选择自己想要的元素
if语句不支持加减乘除,这里可以使用过滤器去代替运算(forloop.counter|divisibleby:2,如果参数是1,则选中的是每一个元素)
{{ hobby }} | {% else %}{{ hobby }} | {% endif %} {% endfor %}
---|
for … empty
if,elif和else
{% if user_list %}
用户人数:{{ user_list|length }}
{% elif black_list %}
黑名单数:{{ black_list|length }}
{% else %}
没有用户
{% endif %}
当然也可以只有if和else
{% if user_list|length > 5 %}
七座豪华SUV
{% else %}
黄包车
{% endif %}
if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断。
with
定义一个中间变量
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
这个标签用于跨站请求伪造保护。
在页面的form表单里面写上{% csrf_token %}
{# … #}
1. Django的模板语言不支持连续判断,即不支持以下写法:
django不支持连续判断
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeIAAADkCAMAAABzGdc4AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAMAUExURf///wAAgdLS0gAAAO/v7/w4OIEAAPHx8f/745nN/5ucm2qPs7b+/v//25mZmWa3/9v///+1ZY/b////t2QEANLx7gBjuDeO2gABZgA5jf/bj444AO/qzLGZme/w4Zm90JmZuOLu7P7h/9qOOPTasQA4wfw6XsapmQAA//7DgjqR9rZlCNW4maPI4/2h3+HGqf//xJmpxD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c3DEcUyAxOL4ki5fvQWloHi6ycFxRcuPHhmiidHqPjwxk3Qe50r53efbEhpOKR4283AhM6aFT3/6T0Xfn+MQlMV8y8EQAc32oHksOLlu2gXPfvaCEhxMANTFP+5KKoerF/BFSh+1u3evnDhC/bJwO0LX47/fdK9/7p7G/pxH8XPF2l/U9wm5Eai+AA6aV4AKUEsiukYCCt+sL6oQUuDLVRMvA0VS4nc+o7690W8dpviNiE1ovjD1qPtQzG7fFdUV1Km+PoRdc4EDbZI8X2QCmHsOuov3eP3J923T8B7qBh+KbCPp4Mb7UBqdLi1fHdFumnQPXqwVar4+yPWiui19TWKfEKdslf89sGz4/cFxdAHwG8IHdxoB1Ljovjb+YOVb1TW/roaUawTAlDxn4s61IJuV4o03EpWDNdjOrjRDoFiHmAdUBynBfGIjloGW7UUX7eOum1IDSt+CEEMI2q6GLPokVQPt2SwNaCYbQ5RbMOt9iE1GsV0X4w9NHbZKZQqdjdNf+pVOVAMNgEcUTvFMt7GrXbTNAFIjVyLYbS1skJ3w4lBPEwxP/pwDzJCxRjGQxXbo49JQGpEcX1YsUcVEzrYagAd3GiHFhQTYJcQR4AbbDVADma0weQUj4MczGgDU5w9pjh7WLHMbR0DP6w2ziKmOHtMcfaY4uwxxdljirPHFGePKc4eU5w9pjh7THH2mOLsMcXZY4qzxxRnjynOHlOcPaY4e0xx9pji7DHF+dLp/D/0q7NVWrBSWAAAAABJRU5ErkJggg==" alt="" width="382" height="128" />
python的比较方法
js的比较方法
.png)aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAb0AAAFNCAMAAACjYkFvAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAMAUExURf///7e3t4GBgZiYmNvb2+/v7/j39/Hx8fs4OIEAAIuLi83Nzd7e3vr5/P39/v04OP2j4f//w6ampvLZ7ujo6O7u+70/qcjIyAwiq5tHBIWFhcHBwevD5drb8asMkfnt98nG8fw4Xj1CuP3h/9N8xaKs4SIiIkBRvbOzsxoA0XR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WVOsm3/TfkKyj1Y5ZPC6BgsHpfoF4xqR9/+evLMZ7RLCQNFu9viFdM6iwe1ixF5fgEd+vFpV6H5wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIC+C4P87bAtROvyHjwAAAABJRU5ErkJggg==" alt="" width="300" height="208" />
2. Django的模板语言中属性的优先级大于方法
def xx(request):
d = {"a": 1, "b": 2, "c": 3, "items": "100"}
return render(request, "xx.html", {"data": d})
如上,我们在使用render方法渲染一个页面的时候,传的字典d有一个key是items并且还有默认的 d.items() 方法,此时在模板语言中:
{{ data.items }}
默认会取d的items key的值。
{% endblock %}
{% block page-main %}
{% endblock %}
{% block page-js %}
{% endblock %}
注意:我们通常会在母板中定义页面专用的CSS块和JS块,方便子页面替换。
在子页面中在页面最上方使用下面的语法来继承母板。
{% extends 'main-model.html' %}
通过在母板中使用{% block xxx %}
来定义"块"。
在子页面中通过定义母板中的block名来对应替换母板中相应的内容。
{% block page-main %}
世情薄
人情恶
雨送黄昏花易落
{% endblock %}
可以将常用的页面内容如导航条,页尾信息等组件保存在单独的文件中,然后在需要使用的地方按如下语法导入即可。
{% include 'navbar.html' %}
{% load static %}
引用JS文件时使用:
{% load static %}
某个文件多处被用到可以存为一个变量
{% load static %}
{% static "images/hi.jpg" as myphoto %}
{% load static %}
或者
{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
实例:link链接
settings中的static名字改变后,两种在文件中直接修改,不影响运行的方法
自定义simpletag
和自定义filter类似,只不过接收更灵活的参数。
定义注册simple tag
@register.simple_tag(name="plus")
def plus(a, b, c):
return "{} + {} + {}".format(a, b, c)
使用自定义simple tag
{% load app01_demo %}
{# simple tag #}
{% plus "1" "2" "abc" %}
写函数
from django import template
register = template.Library()
@register.simple_tag
def plus(arg, arg1, arg2,*args,**kwargs):
print(args)
print(kwargs)
return '{}_{}_{}'.format(arg, arg1, arg2)+'_'.join(args)
在html上渲染页面
{% load mytags %}
{% plus 'heshang' 'very' 'gay' 'dubiao' 'ye' 'very' 'gay'%}
{% plus 'heshang' 'very' 'gay' key='' key2='' %}
多用于返回html代码片段
示例:1
templatetags/my_inclusion.py
from django import template
register = template.Library()
@register.inclusion_tag('result.html')
def show_results(n):
n = 1 if n < 1 else int(n)
data = ["第{}项".format(i) for i in range(1, n+1)]
return {"data": data}
templates/snippets/result.html
templates/index.html
{% load inclusion_tag_test %}
{% show_results 10 %}
示例2:编写分页
在app01下创建一个teplatetags包,在templatepags下创建一个py文件,如:mytags,在py文件中写如下代码:
from django import template
register=template.Library()
@register.inclusion_tag('paginations.html')
def pagination(total,page_num): #接受到参数后,经过整理,将参数返回给paginations.html
return {'num':range(1,total+1),'page_num':page_num}
在templates下创建一个html文件,如:paginations,在html中写如下代码
在要渲染的页面(如:asd.html)中的适当位置写如下代码
{% load mytags %} #引入mytags文件
{% pagination 6 2%} #填写参数6,2,将参数传给pagination
123
手机扫一扫
移动阅读更方便
你可能感兴趣的文章