Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating multiple lists in parallel with Python inside HTML (Flask)

I am building a python web app hosted on pythonanywhere following this tutorial loosely. I am modifying the resulting application to fit my own goal.

Here is my python code that I am using to pass variables to a HTML document in order for them to be added to a table using a for loop:

from flask import Flask, redirect, render_template, request, url_for

app = Flask(__name__)
app.config["DEBUG"] = True

productnames = []
reviews = []

@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "GET":
    return render_template("main.html", reviews=reviews, productnames=productnames)

reviews.append(request.form["review"])
productnames.append(request.form["products"])
return redirect(url_for('index'))

Using the following code within my HTML, I am looping through that list and adding each item to the table:

{% for review in reviews %}
    <tr>
        <td></td>
        <td>{{ review }}</td>
        <td></td>
    </tr>
{% endfor %}

And this works, however, I am trying to iterate through multiple lists and found various statements saying that the zip function was what I was looking for so I changed my HTML code to the following segment and it no longer works.

{% for review, product in zip(reviews, productname) %}
    <tr>
        <td>{{ product }}</td>
        <td>{{ review }}</td>
    <td></td>
</tr>
{% endfor %}

From python anywhere, the error page says "Error code: Unhandled Exception", and the error log through the pythonanywhere dashboard says:

2018-04-24 12:57:23,957:   File "/home/FdScGroup/cloudapp/templates/main.html", line 43, in top-level template code
2018-04-24 12:57:23,957:     {% for review, product in zip(reviews, productnames) %}

How do I get this to work?

Any help appreciated, thank you.

like image 877
Ronan Avatar asked Apr 24 '18 13:04

Ronan


1 Answers

zip() is a python function, not a function to be executed in the template language of Flask (Jinja2).

So apply zip() in the view and pass the result to the template:

return render_template("main.html", reviews_products=zip(reviews, productnames))

Then apply this trick: how to iterate over a list of list in jinja in the template.

like image 80
Davy Avatar answered Sep 19 '22 00:09

Davy