iT邦幫忙

0

Day 19|建立評分系統

  • 分享至 

  • xImage
  •  

Day 12 已經有 1–10 分的評分欄位。今天要把它變成更容易閱讀的評分顯示,並新增依評分排序的功能。
步驟 1:在作品卡片上顯示評分
在 collection.html 中加入:

步驟 2:加入評分樣式
在 style.css 中加入:
.rating {
margin-top: 12px;
}

.rating-score {
display: inline-block;
padding: 4px 10px;
border-radius: 999px;
background: var(--accent);
color: #10131a;
font-weight: 700;
}

.rating-empty {
color: var(--muted);
font-size: 0.9rem;
}

步驟 3:加入評分排序
在電影與遊戲路由中,讀取排序參數:
sort = request.args.get("sort", "newest")sort_options = { "newest": "id DESC", "rating": "rating DESC, id DESC", "title": "title COLLATE NOCASE ASC"}order_by = sort_options.get(sort, sort_options["newest"])query += f" ORDER BY {order_by}"

這裡的 order_by 只能從程式預先定義的字典中取得,不要直接把使用者輸入的排序字串拼入 SQL,避免不安全的 SQL 查詢。
步驟 4:在 collection.html 加入排序選單
排序方式

<option value="newest"
{% if selected_sort == "newest" %}selected{% endif %}>
最新收藏

<option value="rating"
{% if selected_sort == "rating" %}selected{% endif %}>
評分由高到低

<option value="title"
{% if selected_sort == "title" %}selected{% endif %}>
名稱 A–Z

在 render_template() 中加入:
selected_sort=sort

測試
新增評分 4、7、9 的作品,選擇「評分由高到低」,確認高分作品排在前面。沒有評分的作品也應該能正常顯示。


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言