zoukankan      html  css  js  c++  java
  • flask自定义过滤器

    1、通过flask模块中的add_template_filter方法

    • 定义函数,带有参数和返回值
    • 添加过滤器,app.add_template_filter(function,name='')
    • 在模版中使用:{{变量|自定义过滤器}}

    2、使用装饰器完成

    • 定义函数,带有参数和返回值
    • 添加过滤器,@add_template_filter('过滤器名字')
    • 在模版中使用:{{变量|自定义过滤器}}

    py文件

    from flask import Flask
    from flask import make_response, request, render_template,redirect,url_for
    import setting,json
    
    app = Flask(__name__)
    app.config.from_object(setting)
    
    @app.route('/')
    
    def hello_world():
        msg = 'hello everyone hello world'
        li = [3,4,7,2,1,5,9]
        return render_template('test.html',msg=msg,li = li)
    
    #第一种方式
    def replace_hello(value):
        print('-----------',value)
        value = value.replace('hello','')
        print('-----------',value)
        return value.strip() #将替换的结果返回
    
    app.add_template_filter(replace_hello,'replace')
    
    #第二种方式 装饰器
    @app.template_filter('listreverse')
    def reverse_list(li):
        tem_li = list(li)
        tem_li.reverse()
        return tem_li
    if __name__ == '__main__':
        app.run(host='127.0.0.1', port=5000)

    html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>自定义过滤器</title>
    </head>
    <body>
    
    {{ msg }}
    <hr>
    {{ msg|replace }}
    <hr>
    {{ li }}
    {{ li|listreverse }}
    </body>
    </html>
  • 相关阅读:
    转:配置nodemanager启动weblogic服务器
    SUSE Linux下新建Weblogic 10.3非admin服务
    转weblogic 10.3新建域
    mysql 导出慢
    sql 查询效率
    js isnull 赋值方法
    linux 启动weblogic的某服务报错
    linux下oracle 10g的sqlplus无法使用
    union all 取代 select中的case when 提高查询效率
    php版判断是否为ajax请求的小demo
  • 原文地址:https://www.cnblogs.com/fat-girl-spring/p/15261835.html
Copyright © 2011-2022 走看看