请关注公众号:自动化测试实战

现在我们通过查询字符串的方式给render_template传参,我们就要用到flask库的flask.request.args.get()函数先获取参数,在index.html中给url_fornext,最后在login.html函数中通过{{ next }}传值。代码如下:

rendertemplateDemo.py文件

 # coding: utf-8

 from flask import Flask, render_template
import flask app = Flask(__name__) # type: Flask
app.debug = True @app.route('/')
def hello_world(): title = {"tPrize": "key",
"info": {"name": u"Warren",
"age": 18,
"gender": u"男"},
"val": {"title": u'标题',
"content": u'内容'}}
return render_template('post/index.html', **title) @app.route('/login/')
def login(): next = flask.request.args.get('next')
return render_template('login.html', next=next) if __name__ == '__main__':
app.run()

index.html文件

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>这里是title</title>
</head>
<body> {# <p>这段代码被注释了</p>#}
<p>{{ info }}</p>
<a href="{{ url_for('login', next='首页') }}">链接到登录页面</a>
</body>
</html>

login.html文件

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
这是登录页面,它来自{{ next }}。
</body>
</html>

然后执行代码,看到:

点击“链接到登录页面”后:

如果你想指定传值类型是path类型,那么就要给login函数传值了:
修改rendertemplateDemo.py文件的login函数如下:

 @app.route('/login/<next>/')
def login(next): # next = flask.request.args.get('next')
return render_template('login.html', next=next)

另外两个文件不变,然后执行代码:

flask第二十篇——模板【3】-LMLPHP

点击“链接到登录页面”后:

flask第二十篇——模板【3】-LMLPHP

05-11 18:21