Home > Software engineering >  passing variable to a table in flask
passing variable to a table in flask

Time:05-19

I am following this video and everything is working perfectly. The output of a SQL query is saved within a variable that I can call on in another .html page.

so my sql query is:

    @app.route('/all_data')
    def all_data():
        customers = db.get_customers()
        for customer in customers:
            var = customers
        return render_template('all_data.html',var=var)

When calling this {{var}} in all_data.html page the output is for a long tuple:

    ('name','email','comment','gender'),('name','email','comment','gender') etc etc

I am looking to put this {{var}} into a table instead?.. I but am hitting a brick wall in finding out how to do this?

any help would be much appreciated!

CodePudding user response:

Assuming you're using Flask's default template engine (Jinja2), you can simple use a for loop to iterate over the elements of the collection inside the template. The syntax is:

{% for item in items %}
    {{ item }}
{% endfor %}

So simply create an HTML table, and add a row for each item in your var variable. IIRC, Jinja tuples act the same as Python's, so you can probably do something along the lines of:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Comment</th>
            <th>Gender</th>
        </tr>
    </thead>
    <tbody>
    {% for current in var %}
        <tr>
            <td>{{ current[0] }}</td>
            <td>{{ current[1] }}</td>
            <td>{{ current[2] }}</td>
            <td>{{ current[3] }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

I haven't checked it (as I don't have a Flask project available right now), but if my memory serves me right, that's how I would do it

Here's a link to an usefull part of Jinja2's documentation

Also, what is this piece of code for ?

    for customer in customers:
       var = customers

You're iterating over each element of the list, but your never use the customer variable (containing the current element). Instead, you assign the var variable to the customers list multiple times. Assuming customers is a simple Python list, you could remove this loop and simply do return render_template('all_data.html',var=customers)

  • Related