一、引入JinJa2模版
首先我们来对比两段代码,它们实现同样的功能, 都是现实用户信息列表:
1 # 第一段 2 @app.route("/users") 3 def get_users():
# 前面省略逻辑处理过程,得到users列表 4 users = [{"name": "Jack", "age": 25, "city": "NewYork"}, 5 {"name": "Rose", "age": 26, "city": "Beijing"}, 6 {"name": "LiLi", "age": 23, "city": "ShangHai"}] 7 html = """ 8 <table border="1"> 9 <tr> 10 <th>姓名</th> 11 <th>年龄</th> 12 <th>城市</th> 13 </tr>""" 14 for user in users: 15 h = """<tr> 16 <td>%s</td> 17 <td>%s</td> 18 <td>%s</td> 19 </tr>"""%(user['name'], user['age'], user['city']) 20 html += h 21 html += "</table>" 22 return html 23 24 # 第二段 25 @app.route("/users") 26 def get_users_with_tempalte():
# 逻辑处理 27 users = [{"name": "Jack", "age": 25, "city": "NewYork"}, 28 {"name": "Rose", "age": 26, "city": "Beijing"}, 29 {"name": "LiLi", "age": 23, "city": "ShangHai"}] 30 return render_template("users.html", users=users)
1 <table border="1"> 2 <tr> 3 <th>姓名</th> 4 <th>年龄</th> 5 <th>城市</th> 6 </tr> 7 8 {% for user in users %} 9 <tr> 10 <td>{{ user.name }}</td> 11 <td>{{ user.age }}</td> 12 <td>{{ user.city }}</td> 13 </tr> 14 {%endfor%} 15 16 </table>
第一段代码中,将业务逻辑处理与视图展现的html都放在视图函数里,当业务处理逻辑或展现页面较复杂时,整个试图函数将会非常丑陋,难以理解且不易维护。
第二段代码中, 我们将业务逻辑处理与页面展现分开,将展现逻辑转移到模版中,使得代码目的清晰,层次分明,而且在模版中我们可以更好的进行页面渲染,这就是Jinja2模版引擎的魅力。
render_template()函数用于渲染模版,第一个参数表示模版文件名, 我们需要在当前项目路径下创建一个templates文件夹,用来放置html模版文件。随后的参数都是键值对,表示模版中的变量对应的实际值。
二、Jinja2模版中的控制结构
1、if-else语句
{% if name %} <h1>Hello, {{ name }}!</h1> {% else %} <h1>Hello, Stranger!</h1> {% endif %}
2、for循环(见(一)中示例)
3、宏定义
Jinja2中的宏,类似Python中的函数,可供需要时调用,例如对于对于上文展现用户列表的例子,我们可以这样定义:
1 {% macro render_user(user) %} 2 <td>{{ user.name }}</td> 3 <td>{{ user.age }}</td> 4 <td>{{ user.city }}</td> 5 {% endmacro %} 6 7 <table border="1"> 8 <tr> 9 <th>姓名</th> 10 <th>年龄</th> 11 <th>城市</th> 12 </tr> 13 14 {% for user in users %} 15 <tr> 16 {{ render_user(user) }} 17 </tr> 18 {%endfor%} 19 20 </table>
其中:macro表示定义宏, render_user相当于函数名, user即为参数。若是某些宏重复使用率较高, 我们可以将它们保存在一个单独的html文件中,然后通过
{% import 'macros.html as macros %}引入,类似于Python的模块调用过程。
4、模版引用
和宏的引用类似, 我们可将多处重复使用的模版代码保存在单独的文件中,然后在需要的地方引用即可{% include 'common.html' %}
5、模版继承
模版继承类似于Python的继承,我们可以创建一个base.html模版,该模版包含基本的html块结构,通过继承该模版,可省去在每个模版中都书写相似内容的过程,而只突出当前模版的主要功能。
<!--base.html--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Jinja2 Template</title> </head> <body> {% block body %} {% endblock %} </body> </html> <!-- users.html --> {% extends 'base.html' %} {% block body %} {% macro render_user(user) %} <td>{{ user.name }}</td> <td>{{ user.age }}</td> <td>{{ user.city }}</td> {% endmacro %} <table border="1"> <tr> <th>姓名</th> <th>年龄</th> <th>城市</th> </tr> {% for user in users %} <tr> {{ render_user(user) }} </tr> {%endfor%} </table> {% endblock %}
extends关键字表示继承关系, {% block body %}...{% endblock %}实现了body部分内容的个性化展现。
浙公网安备 33010602011771号