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>
  • 相关阅读:
    HttpModule学习总结实例应用读书笔记
    SEO入门教程之入门相关
    HttpHandler学习总结实例应用读书笔记
    服务器安全设置总结(Win2003)
    网站建设合同书
    HTML标签解释大全
    敏捷之痒
    一个google浏览器很意思的东东
    C#访问非托管DLL
    随着DzNT的开源,我将投入到.NET的开发当中
  • 原文地址:https://www.cnblogs.com/fat-girl-spring/p/15261835.html
Copyright © 2011-2022 走看看