[英]How to do nested loops and if statements in Flask/Jinja; create inventory table
我正在嘗試制作一個庫存表來顯示卡片的 ID/名稱。 我讓它在 python 中工作,但我不知道如何將它轉換為 jinja 以顯示在網頁上。
我想獲取用戶庫存中的項目並連續顯示 4 個,然后 go 向下重復一列,如果少於 4 個,則顯示剩余的數量。
我在幫助程序 python 文件(addcards.py)中重新創建了它,看看我是否可以讓它工作而不必處理刷新網頁
應用程序.py
def print_table():
user_inventory = db.execute("SELECT * FROM inventory WHERE user_id = 1") # gets users inventory
items = len(user_inventory) # gets how many items in inventory
columns = 4 # random number of columns wanted in table
rows = math.ceil(items / columns) # number of rows need to fit items
default_col = columns # var for columns that wont change
i = 0 # counter var
for row in range(rows): # makes the number of rows
for col in range(columns): # makes number of columns to print
card_db = db.execute("SELECT * FROM cards WHERE id = ?",
user_inventory[i]["card_id"]) # gets card info from db going through users inventory
print("[" ,card_db[0]["card_name"], "]" , end="") # print the unique id/name of card depending on key
i += 1 # moves counter over to next item in inventory
columns = items - columns # calc to see how many items left to display
if columns >= default_col: # check if items over number of columns wanted
items = columns # sets items leftover
columns = default_col # sets column back to columns wanted for next row
print() # end row
return
addcards.py
@app.route("/inventory", methods=["GET"])
@login_required
def inventory():
user_id = session["user_id"]
user = db.execute("SELECT * FROM users WHERE id = ?", user_id) # Search db for users info
username = user[0]["username"] # Get username from 1st row key="username"
return render_template("inventory.html", username=username)
庫存.html
{% extends "layout.html" %}
{% block title %}
Inventory
{% endblock %}
{% block main %}
<h1>Inventory</h1>
{% endblock %}
我建議你做這樣的事情。 同樣的結果,只是更簡單的代碼來制作 jinja (假設這就是你想要的,如果你在評論中澄清一些不同的東西,我會編輯或刪除它)
我更改了結構,以便 python 將卡片列表傳遞給 jinja。 然后在 jinja 中,它循環遍歷卡片,每次循環索引是設置的列數的倍數時添加一個新行。
Python:
columns = 4
cards = []
user_inventory = db.execute("SELECT * FROM inventory WHERE user_id = 1")
for id in user_inventory:
card_db = db.execute("SELECT * FROM cards WHERE id = ?", id["card_id"])
cards.append(card_db[0]["card_name"])
return render_template("inventory.html", cols = columns, cards = cards)
Jinja (inventory.html):
{% extends "layout.html" %}
{% block title %} Inventory {% endblock %}
{% block main %}
<h1>Inventory</h1>
<span class="inventory">
{%for c in cards%}
[{{c}}]
{%if loop.index%cols == 0%}
<br>
{%endif%}
{%endfor%}
</span>
{% endblock %}
以上將准確顯示您的圖像僅在網頁上顯示的內容。
如果你想變得花哨,你可以只用一張桌子做類似的事情。 這種設置方式的好處是我們不需要更改 python,只需要更改 jinja。
{% block main %}
<h1>Inventory</h1>
<table>
<tr>
{%for c in cards%}
<td>{{c}}</td>
{%if loop.index%cols == 0%}
</tr>
{%endif%}
{%endfor%}
</tr>
</table>
<!-- Borders just for demonstration-->
<style>
td {
border: 1px solid black;
}
</style>
{% endblock %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.