flask的过滤器
过滤器本质就是函数
模版语法中过滤器: {{ 变量名|过滤器(args) }}
常见的过滤器:
1、safe:禁用转译 {{ msg|safe }}
2、capitalize:首字母大写
3、lower和upper 大小写转换
4、title 每个单词首字母大写
5、reverse 反转
6、format格式化
7、truncate 字符串截断
list的操作:
1、first
2、last
3、length
4、sum
5、sort
dict的操作:
案例:
app.py
from flask import Flask from flask import make_response, request, render_template,redirect,url_for import setting,json app = Flask(__name__) app.config.from_object(setting) @app.route('/show') def show(): girls = ["yanan","zhouqiang","nike","puma"] users = [ {"name":"zhouqiang","age":18,"gender":"man","address":"anhuihefei"}, {"name": "zhouqiang", "age": 18, "gender": "man", "address": "anhuihefei"}, {"name": "zhouqiang", "age": 18, "gender": "man", "address": "anhuihefei"}, {"name": "zhouqiang", "age": 18, "gender": "man", "address": "anhuihefei"}, {"name": "zhouqiang", "age": 18, "gender": "man", "address": "anhuihefei"}, {"name": "zhouqiang", "age": 18, "gender": "man", "address": "anhuihefei"}, {"name": "zhouqiang", "age": 18, "gender": "man", "address": "anhuihefei"} ] msg = '<h1>520快乐</h1>' n1 = " i am a girl Do you like" return render_template('test.html',girls = girls,users = users,msg = msg,n1 = n1) # 如果没有找到匹配的,会以空白字符串填充 if __name__ == '__main__': app.run(host='127.0.0.1', port=5000)
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>过滤器使用</title> </head> <body> {{ girls|length }} <br> {{ msg }} {{ msg|safe }} #不会将h1标签进行转义 <br> {{ n1|capitalize }} <br> {{ n1|upper }} <br> {{ n1|lower }} <br> {{ n1|reverse }} <br> {{ '%s is %d years old'|format('lily',18) }} <br> {{ n1|truncate(15) }} {{ n1|truncate(15)|upper }} <br> <hr> {{ girls|first }} <br> {{ girls|last }} <br> {{ girls|length }} <br> {#{{ girls|sum }}整型计算#} {{ [1,2,4,32,5]|sum }} <br> {{ [1,4,3,2,5,6,32,23,25]|sort }} <br> <hr> <p> {{ users.0 }} <br> {% for v in users.0.values() %} <p>{{ v }}</p> {% endfor %} <hr> {% for key in users.0.keys() %} <p>{{ key }}</p> {% endfor %} <hr> {% for key,value in users.0.items() %} <p>{{ key }} -- {{ value }}</p> {% endfor %} </p> </body> </html>