在Django中自定义Tag和Filter(二)

这篇文章中介绍下如何自定义fliter。

1.首先如上一篇所叙述一样先建立一个项目app,创建方式参考上一篇。

2.在项目中建一个名字为templatetags的包,名字必须是templatetags。

3在这个包中过滤器文件如filters.py,内容如下

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright(C) 2008 SupDo.com
# Licensed under the GUN License, Version 3.0 (the "License");
# 
# File:        filters.py
# Author:      KuKei
# Create Date: 2008-10-09
# Description: 自定义过滤器。
# Modify Date: 2008-10-09
    
from supdo import settings
from datetime import timedelta
from django.template import Library, defaultfilters
    
register = Library()
    
def datetz(value,arg):
    tomezone = settings.TZ
    if '+' == tomezone[0] :
        value += timedelta(seconds=int(tomezone)*60*60)
    elif '-' == tomezone[0] :
        value -= timedelta(seconds=int(tomezone)*60*60)
    
    return defaultfilters.date(value, arg)
    
register.filter(datetz)

4.在模板中使用此过滤器,首先在使用之前先载入自定义的过滤器,然后使用,示例代码如下:

{ % load filters % }    
{{log.date|datetz: "Y-m-j f A" }}

这样一个自定义的过滤器就实现了。

其实这示例中的过滤器是解决gae时区问题的自定义过滤器

 

你可能感兴趣的:(在Django中自定义Tag和Filter(二))