zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    网络编程2018-4-23
    网络编程
    异常处理
    在Asp.net core使用配置Json创建动态目录树
    Asp.net Core中文转换成拼音
    解决Asp.Net core 控制台出现乱码的情况
    解决Asp.net Core中chtml文档中文乱码的问题
    取代Ajax.BeginForm的ajax使用方法
    将数据库模型放入到.Net Core的类库中
    如何使用Resource资源文件
  • 原文地址:https://www.cnblogs.com/sysnap/p/6560466.html
Copyright © 2011-2022 走看看