I am working on a flask app that gets data from a database and should render this in on a page template. It is working okish, but there is the request to display data differently. I am now looking how I can do this best.
The data is an example, my data set has up to 20 columns and more than 1000 rows
Assume the SQL table looks like this:
| State | City | Population |
|---|---|---|
| Alabama | Huntsville | 220k |
| Alabama | Montgomery | 199k |
| Alabama | Birmingham | 198k |
| Alabama | Mobile | 185k |
| Alaska | Anchorage | 288k |
| Alaska | Fairbanks | 33k |
| Alaska | Juneau | 32k |
| Arizona | Phoenix | 1,625k |
| Arizona | Tucson | 543k |
| Arizona | Mesa | 509k |
The data is going directly to a dict which is passed to jinja2
cursor.execute("SELECT State , City , Population from table")
result = cursor.fetchall()
return render_template('template.html', results = results)
in Jinja2 it looks like this:
{% for result in results %}
<tr>
<td>{{result['State']}}</td>
<td>{{result['City']}}</td>
<td>{{result['Population']}}</td>
</tr>
{% endfor %}
Now the request is to deliver the output in div with a structure like this:
Alabama
-- Huntsville 220k
-- Montgomery 199k
-- Birmingham 198k
Alaska
-- Anchorage 228k
-- Fairbanks 33k
-- Juneau 32k
The jinja loop could be something link this
{% for states in results %}
<div>
<div>{{result['State']}}</div>
<div>
{% for cities in results %}
{% if states['State'] == cities ['State'] %}
<div>--</div>
<div>{{result['City']}}</div>
<div>{{result['Population']}}</div>
{% endif %}
{% endfor %}
</div>
</div>
{% endfor %}
what is the best way to loop this dictionary again? Would it be better if the data would be prepared differently before putting into the template?
I am not looking for the exact code, but some input what could be a great approach.