在Jinja2模板中使用复杂数据

独自空忆成欢 提交于 2020-01-19 16:20:22

在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()
  • 结果呈现

在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!