案例1
- templates目录下新建filter.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ user.username }}-{{ user.username|length }}
</body>
</html>
from flask import Flask, render_template
app = Flask(__name__)
class User:
def __init__(self,username,email):
self.username = username
self.email = email
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/filter')
def filder():
user = User(username="goudan",email="gd@qq.com")
return render_template("filter.html",user=user)
if __name__ == '__main__':
app.run()
- 启动服务,访问http://127.0.0.1:5000/filter,username有6个字符
自定义过滤器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ user.username }}-{{ user.username|length }}
<div>{{ mytime|dformat }}</div>
</body>
</html>
import datetime
from flask import Flask, render_template
app = Flask(__name__)
# 添加过滤器
def datetime_format(value, format="%Y-%d-%m %H:%M"):
return value.strftime(format)
app.add_template_filter(datetime_format,"dformat")
class User:
def __init__(self,username,email):
self.username = username
self.email = email
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/filter')
def filder():
user = User(username="goudan",email="gd@qq.com")
# 获取当前时间
mytime = datetime.datetime.now()
return render_template("filter.html",user=user,mytime=mytime)
if __name__ == '__main__':
app.run()
- 访问