过滤器
过滤器是个函数,参数就是管道(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(value, case_sensitive=False, by='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.