Search code examples
htmlflaskhrefnested-loops

Flask - Making HTML table of hyperlinks via nested for-loops?


I'm designing a Flask application that works with a MySQL database.

I have this Flask code below:

@app.route("/test")
def test():
cursor.execute("SELECT * from testtable;")
data = cursor.fetchall()
return render_template('test.html', data = data)

I wish to make an HTML table from this data, and I want the first column of this table to be hyper-linked. My current test.html is shown below:

<table border="1" cellpadding="5" cellspacing="5">
{% for row in data %}
<tr>
{% for d in row %}  
    <td><a href="/testresult?query={{ d }}">{{ d }}</a></td>
{% endfor %}
</tr>
{% endfor %}
</table>

This HTML makes a hyper-link out of every cell in every column of the table. Is there a way to make only the cells in the first column be hyper-linked, and make all other cells just show {{ d }}?


Solution

  • The default template engine in Flask is jinja2.

    In jinja2 you can check the loop index, which means that you could do something like the following.

    {% for d in row %}
      {% if loop.index == 1 %} # You can also use loop.index0 for 0-based indexing
        <td><a href="/testresult?query={{ d }}">{{ d }}</a></td>
      {% else %}
        <td>{{ d }}</td>
      {% endif %}
    {% endfor %}
    

    You can also skip the first element in the row list by using the following syntax:

    {% for d in row[1:] %}