• 过滤器


    过滤器本质是函数 作用: 不仅需要输出变量的值, 还需要修改变量的显示.

    使用方式: 变量名|过滤器

    常用内置过滤器:

    字符串操作

    • safe:禁用转义
    <p>{{ '<em>hello</em>' | safe }}</p>
    
    • capitalize:把变量值的首字母转成大写,其余字母转小写
    <p>{{ 'hello' | capitalize }}</p>
    
    • lower:把值转成小写
    <p>{{ 'HELLO' | lower }}</p>
    
    • upper:把值转成大写
    <p>{{ 'hello' | upper }}</p>
    
    • title:把值中的每个单词的首字母都转成大写
    <p>{{ 'hello' | title }}</p>
    
    • reverse:字符串反转
    <p>{{ 'olleh' | reverse }}</p>
    
    • format:格式化输出
    <p>{{ '%s is %d' | format('name',17) }}</p>
    
    • striptags:渲染之前把值中所有的HTML标签都删掉
    <p>{{ '<em>hello</em>' | striptags }}</p>
    
    • truncate: 字符串截断
    <p>{{ 'hello every one' | truncate(9)}}</p>
    

    列表操作

    • first:取第一个元素
    <p>{{ [1,2,3,4,5,6] | first }}</p>
    
    • last:取最后一个元素
    <p>{{ [1,2,3,4,5,6] | last }}</p>
    
    • length:获取列表长度
    <p>{{ [1,2,3,4,5,6] | length }}</p>
    
    • sum:列表求和
    <p>{{ [1,2,3,4,5,6] | sum }}</p>
    
    • sort:列表排序
    <p>{{ [6,2,3,1,5,4] | sort }}</p>
    

    语句块过滤

    {% filter upper %}
        #一大堆文字#
    {% endfilter %}
    自定义过滤器 : 1 通过Flask应用对象的add_template_filte方法
    def do_listreverse(li):
        # 通过原列表创建一个新列表
        temp_li = list(li)
        # 将新列表进行返转
        temp_li.reverse()
        return temp_li
    
    app.add_template_filter(do_listreverse,'lireverse')

    2.通过装饰器实现
    @app.template_filter('lireverse')
    def do_listreverse(li):
        # 通过原列表创建一个新列表
        temp_li = list(li)
        # 将新列表进行返转
        temp_li.reverse()
        return temp_li

    • 在 html 中使用该自定义过滤器
    <br/> my_array 原内容:{{ my_array }}
    <br/> my_array 反转:{{ my_array | lireverse }}
  • 相关阅读:
    Lintcode: Two Strings Are Anagrams
    Leetcode: House Robber
    Leetcode: Binary Tree Right Side View
    Leetcode: Number of Islands
    Lintcode: Subarray Sum
    Lintcode: Sort Letters by Case
    Lintcode: Sort Colors II
    Lintcode: Single Number III
    Lintcode: Search Range in Binary Search Tree
    Lintcode: Binary Tree Serialization (Serialization and Deserialization Of Binary Tree)
  • 原文地址:https://www.cnblogs.com/zxt-cn/p/9126495.html
Copyright © 2020-2023  润新知