• jinja2-过滤器


    过滤器

    过滤器是个函数,参数就是管道(pipe)前面那个变量。比如  123|myfilter,123就是myFilter的参数。如果需要两个参数,则在myFilter后面加(),即123|myFilter(234)

    主要作用就是 可以在模板中以管道的方式用pyhton的代码处理字符串,过滤器用  |  来使用

    过滤器编写

    filter函数写在app.run前,注册在app.jinja_env.filters中,比如

    app = Flask(__name__)

    # convert dict to string

    def json_dumps(dict):

            result = json.dumps(dict)

            return result

    # return type of arg

    def typeFilter(arg):

            result = type(arg)

            return result

    env = app.jinja_env

    env.filters['json_dumps'] = json_dumps

    env.filters['typeFilter'] = typeFilter

    测试代码

    <body>

    dict is {{ dict|typeFilter}}

    <hr>

     dict | json_dumps is{{ dict|json_dumps |typeFilter}}

    <hr>

    you can use json_dumps filter to send dict to js,remember to add safe filter,<br>

    press f12 to test it

    </body>

    <script>

        //you can use json_dumps filter to send dict to js,remember to add safe filter

        console.log({{ dict |json_dumps|safe}})

    </script>

    内置过滤器

    capitalize(s) 首个字母大写

    Capitalize a value. The first character will be uppercase, all others lowercase.

    dictsort(valuecase_sensitive=Falseby='key') 字典排序

    Sort a dict and yield (key, value) pairs. Because python dicts are unsorted you may want to use this function to order them by either key or value:

    {% for item in mydict|dictsort %}
        sort the dict by key, case insensitive
    
    {% for item in mydict|dictsort(true) %}
        sort the dict by key, case sensitive
    
    {% for item in mydict|dictsort(false, 'value') %}
        sort the dict by key, case insensitive, sorted
        normally and ordered by value.

    escape(s) 字符转义

    Convert the characters &, <, >, ‘, and ” in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.

  • 相关阅读:
    Xpath 和Css Selector使用
    JS 基础
    python中requests.session的妙用
    HTML基础之DOM
    吃着火锅唱着歌学会Docker
    SAAS方法论
    Python操作MySQL
    Flask中session实现原理
    人的成长永远不会大于自己的思想
    Serializers 序列化组件
  • 原文地址:https://www.cnblogs.com/sysnap/p/6560466.html
Copyright © 2020-2023  润新知