自定义过滤器
自定义一个提交时间过滤器,假设要发表一篇博客,发表之后会显示距今离发表时过了多长时间
- python文件
from flask import Flask, render_template from datetime import datetime app = Flask(__name__) @app.route("/") def index(): content = { "time": datetime(2020, 10, 17, 22, 0, 0) } return render_template("use_filter.html", **content) @app.template_filter("handle_time") def handle_time(commit_time): now_time = datetime.now() time = (now_time - commit_time).total_seconds() if time < 60: return "刚刚" elif 60 <= time < 60 * 60: return "%d分钟之前" % int(time / 60) elif 3600 <= time < 3600 * 24: return "%d小时之前" % int(time / 3600) if __name__ == '__main__': app.run(debug=True)
- html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>博客发表时间于{{ time | handle_time }}</p> </body> </html>
- 结果