Skip to content
Advertisement

Display documents in a table from MongoDB with Jinja2 HTML

I currently try to figure out how to display multiple documents from my MongoDB collection “one by one”. My recent code to fetch the data looks like this:

@app.route('/shops', methods=['GET', 'POST'])
@login_required
def certified_shops():
    shopdata = col.find({ "go": True})

    return render_template("tables.html", shopdata=shopdata)

My HTML Jinja injection like this:

<tr>
<td>   
{% for data in shopdata: %}
 {{ data.url_name }}
{% endfor %}
</td>
</tr>

The code itself works fine – but literally all URLs are displayed in one row of course.

Right now I can’t find a good way to handle this. I just tried to displaying the data with a different loop or some “in range”, but this doesn’t worked so far. Everything i found here or in the documentation for mongodb and jinja didn’t went well for me. Might there be an easy trick with my html handling or the db query to display one url for each td/tr easy and flexible ? Since the collection will grow, the list should automatically expand in my web application.

Would love to here some ideas since I’ve been racking my brain for days now without any good solutions and I’ve been thinking that there must be an easy way and I just can’t see it because it’s that simple.

Advertisement

Answer

Did I understand your question well? This will create a new row for every url_name:

{% for data in shopdata %}
  <tr>
    <td>   
      {{ data.url_name }}
    </td>
  </tr>
{% endfor %}

Notice. No colon (:) used in the jinja for loop after ‘shopdata’.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement