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

2024-09-30 22:12:12 发布

您现在位置:Python中文网/ 问答频道 /正文

<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循环创建一个表,变量在flask框架中传递,“items”将始终与三个列表(Description、location和status)的长度相同。 我知道以下问题: 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)

Tags: infordatastatustableitemsrangelocation
1条回答
网友
1楼 · 发布于 2024-09-30 22:12:12

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

<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 %}

相关问题 更多 >