在Jinja2模板中传递列表、字典、对象
在模板文件中,要引用内部变量的值。如传递一个列表mylist,需在模板文件中使用mylist[0],mylist[1]引用列表中的元素。传递一个字典,需在模板文件中使用mydict[‘key’]引用key对应的value
实例:向模板文件template.txt(template.html)传递4种复杂类型的数据,并在模板文件中输出这些复杂类型数据中相应的值
- template.txt
此处使用txt和html格式的文件均可,数据形式一样
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Jinja2模板测试</title>
</head>
<body>
<h1>字典:{{mydict['type']}}</h1>
<h1>列表:{{mylist[0]}}</h1>
<h1>函数:{{myfunc()}}</h1>
<h1>对象:{{myclass.func()}}</h1>
</body>
</html>
- template_Jinja2.py
from flask import Flask,render_template
app=Flask(__name__)
###在模板文件中会访问该类的实例
class MyClass:
def func(self):
return 'func'
###在模板文件中会调用该函数
def myfunc():
return 'myfunc'
###定义根路由,通过template.txt模板向客户端返回数据
@app.route('/')
def index():
##要传递给模板文件的字典
mydict={}
mydict['type']='dict'
##要传递给模板文件的列表
mylist=[]
mylist.append('list')
myclass=MyClass()
##通过render_template函数装载模板文件,并通过关键字参数传递给模板文件4个值
return render_template('template.html',mydict=mydict,
mylist=mylist,myclass=myclass,myfunc=myfunc)
if __name__=="__main__":
app.run()
- 结果呈现
来源:CSDN
作者:不才~
链接:https://blog.csdn.net/qq_45323012/article/details/104040765