展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

过滤器

案例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>
  • app.py
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个字符

自定义过滤器

  • filter.html
<!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>
  • app.py
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()
  • 访问
posted @ 2024-03-19 15:50  DogLeftover  阅读(5)  评论(0编辑  收藏  举报