django模板常用过滤器—add、cut

add过滤器:将两个数相加或拼接

views.py

def add(request):
    context={'l1':[1,'hello','hi'],'l2':['nice',True]}
    return render(request,'add.html',context=context)

add.html

……
<body>
  <p>{{ 4|add:2|add:6}}</p>  <!--12-->
  <p>{{ '4'|add:'hello' }}</p>  <!--4hello-->
  <p>{{ l1|add:l2 }}</p>  <!--[1,'hello','hi','nice',True]-->
  <!--不能将整数和字符串拼接,否则会报错,例如{{ 4|add:'hello' }}-->
</body>
……

cut过滤器:去掉一部分

views.py

def cut(request):
    context={'a':'abc','b':'bcd'}
    return render(request,'cut.html',context=context)

cut.html

……
<body>
<p>{{ a|cut:'a' }}</p>  <!--bc-->
<p>{{ 'good job'|cut:' ' }}</p> <!--goodjob-->
</body>
……

猜你喜欢

转载自www.cnblogs.com/Forever77/p/10133384.html