首页 > 代码库 > 自己扩展django的过滤器
自己扩展django的过滤器
/* myfilter.py*/
#coding=utf-8
from django import templateimport time
register = template.Library()
@register.filter(name=‘cut‘)
def cut(value, arg):
return value.replace(arg, ‘‘)
@register.filter
def lower(value):
return value.lower()
@register.filter
def firstPath(value):
maps = {"EngineerUser":"engineer", "SaleUser":"sale", "AdminUser":"admin","Operationer":"operation"}
return maps.get(value, "")
@register.filter
def formatTime(t):
if not t: return ""
strT = time.strftime("%Y-%m-%d %H:%M", time.localtime(t))
return strT
@register.filter
def formatShortTime(t):
if not t: return ""
strT = time.strftime("%Y-%m-%d", time.localtime(t))
return strT
上面是自己扩展django的过滤器,添加自己特有的过滤器,主要语法在上面的黑体粗子, 而@register.filter这个标记,则是Python的装饰器。当你在模板中需要用到自己定义的过滤器时,需要在文件头不写上这样一句话{%load myfilter%},如下的html文件:
mytabel.html:
{% extends "base.html" %}
{%load netbasefilters%}
{% block extra_css %}
<link rel="stylesheet" type="text/css" href=http://www.mamicode.com/"/media/css/serviceNoteList.css" />
{% endblock %}
<table class="data_table" name="listServiceNotes">
<thead>
<tr>
<th>
<span style="width: 15%;" name="subject">主题<em class="downImg updownImg" sortType="{{request.REQUEST.sortType}}"></em></span>
<span style="width: 10%;" name="eventLabel">名称/设备IP<em class="downImg updownImg" sortType="{{request.REQUEST.sortType}}"></em></span>
<span style="width: 10%;" name="monitorObjName">监控项目<em class="downImg updownImg" sortType="{{request.REQUEST.sortType}}"></em></span>
<span style="width: 30%;" name="content">工单信息<em class="downImg updownImg" sortType="{{request.REQUEST.sortType}}"></em></span>
<span style="width: 8%;" name="engineer">工程师<em class="downImg updownImg" sortType="-1"></em></span>
<span style="width: 8%;" name="startTime">开始时间<em class="downImg updownImg" sortType="-1"></em></span>
<span style="width: 8%;" name="endTime">结束时间<em class="downImg updownImg" sortType="-1"></em></span>
<span style="width: 6%;" name="emergencyDegree">紧急程度<em class="downImg updownImg" sortType="-1"></em></span>
</th>
</tr>
</thead>
<tbody>
{% for nt in notes%}
<tr class="data_tr" >
<td>
<span style="width: 15%;">{{nt.subject}}</span>
<span style="width: 10%;">{{nt.eventLabel}}</span>
<span style="width: 10%;">{{nt.monitorObjName}}</span>
<span style="width: 30%;">{% autoescape off %}{{nt.content}}{% endautoescape %}</span>
<span style="width: 8%;">{{nt.engineer.titleOrUid}}</span>
<span style="width: 8%;">{{nt.startTime|formatShortTime}}</span>
{% if request.REQUEST.status == "1"%}<span style="width: 8%;">
{{nt.endTime|formatShortTime}}</span>
{% endif %}
<span style="width: 6%;">{{nt.emergencyDegree}}</span>
</td>
</tr>
{% endfor %}
</tbody>
</table>
就像上面的红色粗体字一样的去使用你的过滤器了
自己扩展django的过滤器