0

I am trying to create a html table using jinj2 template in python. when i render template i only get headers and not rows. can you please correct my code, thank you. below is my python code :

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>

I have used How to build up a HTML table with a simple for loop in Jinja2? as reference.

venkat
  • 31
  • 8

1 Answers1

1

In your case you need to store the x_row as a dict in python and you don't need to pass other parameters like 'user_id', 'metric_count', etc.

Here's how you can rectify your python code:

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)

This way your jinja2 renderer will pick value from list of dict. Cheers!!

Nishant Patel
  • 1,334
  • 14
  • 22