模版中的url_for跟我们后台视图函数中的url_for使用起来基本是一模一样的。也是传递视图函数的名字,也可以传递参数。使用的时候,需要在url_for左右两边加上一个{{ url_for(‘func’) }}
视图:
from flask import Flask,render_template
#todo 初始化Flask项目的服务
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html')
@app.route('/login1/<un>')
def user_login(un):
print(un)
return 'ok,用户名{}'.format(un)
if __name__ == '__main__':
#0.0.0.0:代表当前的系统的所有的ip地址,
# 设置端口为8080,
# flask的debug模式:把错误的信息显示到页面中
app.run(host='0.0.0.0',port=8080,debug=True)
模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="{{ url_for('user_login',un='zilv',id=2) }}">登录</a>
{#<img src="{{ url_for('static',filename='3.jpg') }}">#}
</body>
</html>
点击登录按钮,渲染模板