本文总结了两种方法:全局变量和类方法
1、全局变量示例代码:
from flask import Flask, render_template
app = Flask(__name__)
ret = []
@app.route("/index")
def index():
s = "I love you!"
t = "Me Too!"
global ret
ret.append(s)
ret.append(t)
return render_template("index.html", m=ret)
@app.route("/index2")
def index2():
global ret
return render_template("index2.html", n=ret)
if __name__ == "__main__":
app.run(debug=True)
index.html
flask框架
{{ m }}
index2.html
flask框架2
{{ n }}
运行效果:
2、类方法
示例代码:
from flask import Flask, render_template
app = Flask(__name__)
class DataBase(object):
x = None
y = None
z = None
data = DataBase()
@app.route("/index")
def index():
s = "I love you!"
t = "Me Too!"
m = s + t
data.x = s * 3
data.y = t * 2
return render_template("index.html", m=m)
@app.route("/index2")
def index2():
n = data.x + data.y
return render_template("index2.html", n=n)
if __name__ == "__main__":
app.run(debug=True)
index.html
flask框架
{{ m }}
index2.html
flask框架2
{{ n }}
运行效果:
注意事项:
步骤1.创建一个名为“ templates”的新文件夹
步骤2.将“ index.html”移动到“ templates”文件夹中
步骤3.在索引函数中,返回render_template('index.html',m = m)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)