11 {% block body %}{% endblock %}12
13
14 ```15 可以看到,在``标签中使用了if判断,如果给模板传递了`page_title`变量,显示之,否则,不显示。16 ``标签中定义了一个名为`body`的block,用来被其他模板文件继承。17 ### 11.3 创建并编辑HelloWorld/templates/user_info.html
18 内容如下:19 ```20 {% extends "default.html" %}21
22 {% block body %}23 {% for key in user_info %}24
25 {{ key }}: {{ user_info[key] }}26
27
28 {% endfor %}29 {% endblock %}
变量user_info应该是一个字典,for循环用来循环输出键值对。
3、编辑 server.py
1 from flask importFlask, render_template2
3 app = Flask(__name__)4
5
6 @app.route('/')7 defhello_world():8 return 'hello world'
9
10
11 @app.route('/user')12 defuser():13 user_info ={14 'name': 'letian',15 'email': '123@aa.com',16 'age':0,17 'github': 'https://github.com/letiantian'
18 }19 return render_template('user_info.html', page_title='letian\'s info', user_info=user_info)20
21
22 if __name__ == '__main__':23 app.run(port=5000, debug=True)
render_template()函数的第一个参数指定模板文件,后面的参数是要传递的数据。
4、运行与测试
运行HelloWorld/server.py,在浏览器中访问http://127.0.0.1:5000/user,效果图如下:
查看网页源码:
1
2
3
4 letian's info5
6
7
8 name: letian
9 email: 123@aa.com
10 age: 0
11 github: https://github.com/letiantian
12