• flask模板和过滤器及自定义过滤器的使用


    模板

    Falsk中的render_template函数用于返回一个模板
    render_template函数的第一个参数是模板的文件名,后面的参数都是键值对,表示模板中变量对应的真实值。
    
    @app.route('/')
    def index():
        lists = [i*2 for i in range(20)]
        my_dict = {'a':'aa','b':'bb'}
        return render_template('index.html',
                    my_dict=my_dict,
                    lists = lists
        )
    
    # 注意,模板名后面传入的是键值对,不是字典,
    # 键作为模板中操作的对象.

    过滤器

    • 字符串操作
    禁用转义:{{ '<em>hello</em>' | safe }}
    删除标签:{{ '<em>hello</em>' | striptags }}
    首字母大写:{{ 'hello' | capitalize }}
    所有值小写:{{ 'HELLO' | lower }}
    首字母大写:{{ 'hello world' | title }}
    字符串反转:{{ 'hello' | reverse }}
    字符串截断:{{ 'hello world' | truncate(5) }}什么鬼?
    • 列表操作
    获取列表长度:{{ [1,2,3,4,5,6] | length }}
    列表求和:{{ [1,2,3,4,5,6] | sum }}
    列表排序:>{{ [6,2,3,1,5,4] | sort }}

    自定义过滤器

    • 方式一:
      通过Flask应用对象的add_template_filter方法
    def list_reverse(li):
        temp = list(li)
        temp.reverse()
        return temp
    
    # 可以给过滤器器一个名字,如果没有,默认就是函数的名字
    app.add_template_filter(list_reverse,'li_reverse')


    • 方式二:

    通过装饰器来实现自定义过滤器
    # 使用装饰器事项过滤器,
    # 如果不传入参数,默认过滤器名字就是函数的名字    
    @app.template_filter()
    def my_filter(args):
        temp = list(args)
        temp.reverse()
        return temp

  • 相关阅读:
    BP神经网络模型
    支持向量机-分类器之王
    逻辑回归
    git常用命令总结持续更新
    gitlap安装配置网络这个坑
    mysql简单备份脚本
    mysql的my.cnf文件详解
    二进制部署mysql5.6
    CMDB学习之七-实现采集错误捕捉,日志信息处理
    CMDB学习之八,完成所有资产采集信息的收集
  • 原文地址:https://www.cnblogs.com/fanlei5458/p/9235464.html
Copyright © 2020-2023  润新知