Python FLask:模板
来自CloudWiki
目录
渲染模板
Flask在templates子文件夹中去寻找模板,
模板一
templates/index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>Welcome to Flask</h1> </body> </html>
模板二
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Hello, {{ name }}!</h1> </body> </html>
调用模板
from flask import Flask,render_template app = Flask(__name__) @app.route('/') def hello_world(): return render_template('index.html') # 渲染模板 @app.route('/user/<username>') def show_user_profile(username): # 显示该用户名的用户信息 return render_template('user.html', name=username) # 渲染模板 if __name__ == '__main__': app.run(debug=True)
访问页面
http://127.0.0.1:5000/user/maxin
传递数组给模板
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1> the authors are:<h> {% for i in partners %} <h2>{{i}}</h2> {% endfor %} </body> </html>
python
from flask import Flask,render_template @app.route('/user/') def show_user_profile(): #return 'User: %s' % username a=['zhangsan','lisi','wangwu'] return render_template('author.html', partners=a)
在模板中显示表格
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>卤the authors are:</h1> <table class="table table-striped"> <tr> <th>ID</th> <th>name</th> </tr> {% for i in partners %} <tr> <td>0</td><td>{{i}}</h2> </tr> {% endfor %} </table> </body> </html>
python
@app.route('/info') def show_table_profile(): #return 'User: %s' % username a=['zhangsan','lisi','wangwu'] return render_template('info.html', partners=a)
传递字典给模板
html
<body> <h1>the authors are:</h1> <table id="customers" class="table table-striped"> <tr> <th>ID</th> <th>name</th> </tr> {% for key, value in my_dict.items() %} <tr> <td>{{ key }}</td> <td>{{ value}}</td> </tr> {% endfor %} </table> </body> </html>
python
from flask import Flask from flask import Flask,render_template app = Flask(__name__)#创建一个该类的实例,第一个参数是应用模块或者包的名称 @app.route('/')#告诉Flask 什么样的URL能触发函数 def hello_world(): return 'Hello World!' @app.route('/user/') def show_user_profile(): #return 'User: %s' % username a=['zhangsan','lisi','wangwu'] score={'math':90,'english':95,'chinese':100} return render_template('author.html', my_dict=score) if __name__ == '__main__':#程序入口 #app.run()#让应用运行在本地服务器上。 app.run(debug=True,host='0.0.0.0') #允许任意网址访问本站