渲染模板
- index.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>首页</title> 6 </head> 7 <body> 8 <h1>这是首页</h1> 9 </body> 10 </html>
- 调用模板
1 @app.route('/') 2 def index(): 3 return render_template('index.html')
- 效果
渲染变量
- variable.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>变量使用</title> 6 </head> 7 <body> 8 <h1>我的兴趣爱好时:{{ hobby }}</h1> 9 </body> 10 </html>
- 调用模板
1 @app.route('/variable') 2 def variable(): 3 hobby = '游戏' 4 return render_template('variable.html', hobby=hobby)
- 效果
变量为字典和对象
- variable.htm
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>变量使用</title> 6 </head> 7 <body> 8 <h1>我的兴趣爱好时:{{ hobby }}</h1> 9 <p>person 的姓名是:{{ person.name }},person 的年龄是:{{ person.age }}</p> 10 <p>user 的用户名是:{{ user.username }},user 的邮箱是:{{ user.email }}</p> 11 </body> 12 </html>
- 调用模板
1 @app.route('/variable') 2 def variable(): 3 hobby = '游戏' 4 person = { 5 "name": "张三", 6 "age": 18 7 } 8 user = User("李四", "[email protected]") 9 return render_template('variable.html', hobby=hobby, person=person, user=user)
- 效果
变量较多的情况
- 使用**语法
1 @app.route('/variable') 2 def variable(): 3 hobby = '游戏' 4 person = { 5 "name": "张三", 6 "age": 18 7 } 8 user = User("李四", "[email protected]") 9 context = { 10 "hobby": hobby, 11 "person": person, 12 "user": user 13 } 14 return render_template('variable.html', **context)
标签:Flask009,person,html,user,使用,variable,hobby,模板 From: https://www.cnblogs.com/2018jason/p/17434646.html