過濾器
過濾器是個函數,參數就是管道(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.