自定义模板过滤器

#自定义过滤器
@app.template_filter('cut')
def cut(value):
    value = value.replace('hello','')
    return value

======================
前端模板使用
<!--使用自定义的过滤器-->
    <p>{{ article|cut }}</p>

如何自定义时间过滤器

#自定义过滤时间
@app.template_filter('handle_time')
def handle_time(time):
    '''
    1.理清思路
    2.如果小于1分钟,就显示刚刚
    3.如果大于1分钟小于1小时,就显示多少分钟
    4、如果大于1小时小于24小时,就显示多少小时
    5.如果大于24小时小于30天,就显示多少天
    6、否则就是显示原来时间
    :param time:首先要判断一下,他是不是datatime类型
    :return:
    '''
    if isinstance(time,datetime):
        now = datetime.now()
        #统计为时间戳
        timestamp = (now-time).total_seconds()
        if timestamp < 60:
            return '刚刚'
        elif timestamp < 60*60:
            return '{minutes}分钟前'.format(minutes = int(timestamp/60))
        elif timestamp < 60 * 60 * 24:
            return '{hours}小时前'.format(hours = int(timestamp/(60*60)))
        elif timestamp < 60 * 60 * 24 * 30:
            return "{days}天前".format(days = int(timestamp/(60 * 60 * 24)))
        else:
            return time.strftime('%Y-%m-%d %H:%M')
    return time

页面展示

<!--自定义过滤时间-->
    <p>发表时间:{{ create_time|handle_time }}</p>

 datatime复习

from datetime import datetime

create_time = datetime(2018,5,25,0,0)

now = datetime.now()

cost_time = now-create_time

print(cost_time)
print(type(cost_time))

print((now-create_time).total_seconds()) #求花费的总秒数
posted @ 2018-09-19 19:11  python成长中  阅读(204)  评论(0编辑  收藏  举报