试图使用jinja模板创建html表,但无效

2024-04-20 08:42:30 发布

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

我正在尝试使用python中的jinj2模板创建一个html表。当我渲染模板时,我只获取标题而不获取行。请你更正我的密码,谢谢。 下面是我的python代码:

Result1 = connection.execute(query)
Resultset = Result1.fetchall()
text1 = Template('Hi! $name this is test email.')
for row in Resultset:
    x_row = row
    print(x_row)
    user_id = row[0]
    metric_count = row[1]
    query_count = row[2]
    total_usage = row[3]
    print(user_id)
    

    # Create the plain-text and HTML version of your message

   # text = """text1.substitute(name=row[0])"""

    with open("main.html", 'r') as html_file:
        html = html_file.read()
        template = Template(html)
        html_template = template.render(user_id=user_id,
                                        metric_count=metric_count,
                                        query_count=query_count,
                                        total_usage=total_usage,
                                        row=x_row)

And my html code:
<table>

        <tr>
            <th>User Name</th>
            <th>Metric Count</th>
            <th>Queries Count</th>
            <th> Total Memory Usage</th>
        </tr>
        <tbody>
        {% for item in row %}
        <tr>
            <td>{{ item.user_id }}</td>
            <td>{{ item.metric_count }}</td>
            <td>{{ item.query_count }}</td>
            <td>{{ item.total_usage }}</td>
        </tr>
        {% endfor %}
        </tbody>
    </table>

我使用了How to build up a HTML table with a simple for loop in Jinja2?作为参考


Tags: inidforhtmlcountusageitemquery
1条回答
网友
1楼 · 发布于 2024-04-20 08:42:30

在本例中,您需要在python中将x_行存储为dict,而不需要传递其他参数,如“user_id”、“metric_count”等

以下是如何更正python代码:

Result1 = connection.execute(query)
Resultset = Result1.fetchall()
text1 = Template('Hi! $name this is test email.')
x_rows = []
for row in Resultset:
    print(x_row)
    x_row.append({
    'user_id': row[0],
    'metric_count': row[1],
    'query_count': row[2],
    'total_usage': row[3]
    })
    print(user_id)

    with open("main.html", 'r') as html_file:
        html = html_file.read()
        template = Template(html)
        html_template = template.render(row=x_rows)

这样,jinja2渲染器将从dict列表中选择值。 干杯

相关问题 更多 >