使用 jinja2、html 和 flask 构建动态 table

Building a dynamic table with jinja2, html and flask

<table style="width:100%", border="1">
        {% for item in items %}    
        <tr>               
            <td>{{Description[item]}}</td>
            <td>{{Location[item]}}</td>
            <td>{{Status[item]}}</td>                
        </tr>
        {% endfor %}    
</table>

我正在尝试使用此 for 循环创建一个 table,变量在 flask 框架中传递,'items' 将始终与三个列表的长度相同(说明,位置和状态)。 我知道以下问题: How to build up a HTML table with a simple for loop in Jinja2?

但我看不出我的代码与这个问题的有效答案有何不同,是因为我使用的是列表而不是字典吗?

这是 flask 框架,其中列出了 使用渲染模板创建并传递:

def index():
description = []
location = []
status = []
imix80m = ''
imix = ''
with open('behavepretty.json') as a:
    data = json.load(a)
    for n in range(0,len(data)):
        i = 0
        for i in range(0, len(data[n]['elements'])):
            x = data[n]['elements'][i]['name']
            description.append(x)
            y = data[n]['elements'][i]['location']
            location.append(y)
            z = data[n]['elements'][i]['status']
            status.append(z)
        n = 0
    for n in range(0,len(data)):
        if n == 0:
            imix80m = data[n]['status']
        elif n == 1:
            imix = data[n]['status']
a.close()
return render_template('trial.html', Description = description, Location= location, Status = status, result1 = imix80m, result2 = imix, jfile = data, items = description)

你只需要一个循环计数器:

<table style="width:100%", border="1">
        {% for item in Description %}    
        <tr>               
            <td>{{Description[loop.index0 ]}}</td>
            <td>{{Location[loop.index0]}}</td>
            <td>{{Status[loop.index0]}}</td>                            
        </tr>
        {% endfor %}    
</table>

或者,您可以将 3 个打包成一个列表列表:

my_list = [[Description0, Location0, Status0], [Description1, Location1, Status1], ...]

然后:

    {% for item in my_list %}    
        <tr>               
            <td>{{ my_list[0] }}</td>
            <td>{{ my_list[1] }}</td>
            <td>{{ my_list[2] }}</td>                            
        </tr>
    {% endfor %} 

或者,更稳健,字典列表:

my_list = [
    {
        "description" : xxx, 
        "location" : yyy, 
        "status" : zzz
    },
    {
        "description" : www, 
        "location" : eee, 
        "status" : rrr
    },
    ...
]

然后:

    {% for item in my_list %}    
        <tr>               
            <td>{{ item.description }}</td>
            <td>{{ item.location }}</td>
            <td>{{ item.status }}</td>                            
        </tr>
    {% endfor %}