FLASK学习记录-Jinja2模块引擎
Flask中引入了jinja2模板引擎,可以显示动态数据、数据过滤、语句控制、模板继承和引用等。
实战实例
app.py
from flask import Flask,render_template app = Flask(__name__) @app.route('/') def index(): LibraryName="National Library" visitor={ "name":"Jack", "storey":"Computer" } categoryName=["Python","Linux","Flask"] return render_template("index.html",LibraryName=LibraryName,visitor=visitor,categoryName=categoryName) if __name__ == '__main__': app.run(host='0.0.0.0',port=8000,debug=True)
index.html
mkdir templates && cd templates
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> {# National Library #} <h1>{{ LibraryName }}</h1> <h2>Dear {{ visitor.name }},</h2> <h3>Wellcome to {{ LibraryName }} ,as for {{ visitor.storey }} Professional Scholars</h3> <h3>looking for : {% for category in categoryName %} {{category}}, {% endfor %}books </h3> </body> </html>
结果:
控制语句if
{% if condition %}
{% elif condition %}
{% else condition %}
{% endif %}
控制语句for
{% for i in arrays %}
...
{% endfor %}
Jinja2过滤器
过滤器是通过管道符(|)进行使用的,例如{{uuid|length}},将返回uuid的长度
app.py
from flask import Flask,render_template app = Flask(__name__) @app.route('/') def index(): return render_template("filter.html") @app.template_filter() def format1(phone): return phone[0:3]+"****"+phone[-4:] def format2(phone): return phone[0:3]+"****"+phone[-4:] app.add_template_filter(format2,"f2") if __name__ == '__main__': app.run(host='0.0.0.0',port=8000,debug=True)
filter.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>内置过滤器</title> </head> <body> <p>{{'well done'|upper }} </p> <p>{{'well done'|first }} </p> <p>{{'well done'|last }} </p> <p>{{ 'well done'|count }}</p> <p>{{ 'well done'|random }}</p> <p>{{ 1.23456789|round }}</p> <p>{{ 1.23456789|round(2,'floor') }}</p> <p>{{ [3,2,1,9,7]|sort }}</p> <p>{{ [3,2,1,9,7]|join('-') }}</p> <p>{{"<script>alert('good')</script>" }}</p> {# <script>alert('good job')</script> #} <p>{{"<script>alert('good')</script>"|escape }}</p>{# script>alert('good')</script> #} <p>{{"<script>alert('good')</script>"|safe }}</p>{#弹出对话框 #} <p>{{ "<" }}</p>{# < #} <p>{{ "<"|escape }}</p>{# < #} <p>{{ "<"|safe }}</p>{# < #} <p>{{ "16889753210"|format1 }}</p> <p>{{ "16889753210"|f2 }}</p> </body> </html>
结果: