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

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

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

rendertemplateDemo.py文件

 1 # coding: utf-8
 2 
 3 from flask import Flask, render_template
 4 import flask
 5 
 6 app = Flask(__name__)  # type: Flask
 7 app.debug = True
 8 
 9 @app.route('/')
10 def hello_world():
11 
12     title = {"tPrize": "key",
13              "info": {"name": u"Warren",
14                       "age": 18,
15                       "gender": u""},
16              "val": {"title": u'标题',
17                      "content": u'内容'}}
18     return render_template('post/index.html', **title)
19 
20 
21 @app.route('/login/')
22 def login():
23 
24     next = flask.request.args.get('next')
25     return render_template('login.html', next=next)
26     
27 
28 if __name__ == '__main__':
29     app.run()

index.html文件

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>这里是title</title>
 6 </head>
 7 <body>
 8 
 9 {#    <p>这段代码被注释了</p>#}
10     <p>{{ info }}</p>
11     <a href="{{ url_for('login', next='首页') }}">链接到登录页面</a>
12 </body>
13 </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函数如下:

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

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

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

原文地址:https://www.cnblogs.com/captainmeng/p/8716457.html