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.

 

转载于:https://www.cnblogs.com/sysnap/p/6560466.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值