Skip to content

如何在Jinja2模板中使用复杂数据,如Python列表 #119

@Sogrey

Description

@Sogrey
from flask import *

app = Flask(__name__)

class MyClass:
    def func(self):
        return 'myclass func'
def myfunc():
    return 'function'

@app.route('/')
def index():
    mydict = {}
    mydict['type'] = 'dict'
    mylist = []
    mylist.append('list')
    myclass = MyClass()

    return render_template('template.txt',mydict = mydict,mylist = mylist,myclass=myclass,myfunc = myfunc)

if __name__ =='__main__':
    app.run()

template.txt

<html>
    <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>

在Jinja2模板中可以向Python语言一样直接使用列表、字典等类型的值,如mylist[0]、mydict['type']等。

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions