使用 HTMX 和 Django 建立待辦事項應用程序,部分無限滾動
這是該系列的第 7 部分,我將在其中記錄我使用 Django 學習 HTMX 的過程,其中我們將按照 HTMX 的文檔來實現待辦事項的無限滾動功能。
如果您想查看該系列的其餘部分,請查看 dev.to/rodbv 以獲得完整清單。
更新部分模板以載入多個項目
當我們實作無限滾動時,我們將必須傳回幾個待辦事項(專案的下一個「頁面」)並將它們載入到我們目前擁有的部分範本中。這意味著稍微改變我們的部分範本的組成方式;目前的設定如下圖所示,其中部分範本負責渲染單一待辦事項:
我們想要反轉順序,讓部分圍繞 for 迴圈:
讓我們在範本 core/templates/index.html 中執行交換:
<ul> <p>Soon we will get back to the template to add the hx-get ... hx-trigger="revealed" bit that performs the infinite scroll, but first let's just change the view to return several items instead of one on the toggle and create operations:<br> </p> <pre class="brush:php;toolbar:false">... previous code def _create_todo(request): title = request.POST.get("title") if not title: raise ValueError("Title is required") todo = Todo.objects.create(title=title, user=request.user) return render( request, "tasks.html#todo-items-partial", # <-- CHANGED {"todos": [todo]}, # <-- CHANGED status=HTTPStatus.CREATED, ) ... previous code @login_required @require_http_methods(["PUT"]) def toggle_todo(request, task_id): todo = request.user.todos.get(id=task_id) todo.is_completed = not todo.is_completed todo.save() return render( request, "tasks.html#todo-items-partial", # <-- CHANGED { "todos": [todo], # <-- CHANGED }, )
檢查內容的測試仍然通過,而且頁面看起來相同,因此我們很好地實現無限滾動本身。
實現無限滾動
在模板上,我們需要向/tasks 設定一個hx-get 請求,其中hx-trigger="revealed" ,這意味著只有當元素即將進入螢幕上可見時才會觸發GET 請求;這意味著我們希望將其設定在清單中最後一個元素之後,並且我們還需要指示要載入哪個「頁面」資料。在我們的例子中,我們將一次顯示 20 個項目。
讓我們相應地更改模板:
<ul> <p>There's an if next_page_number check around the "loading" icon at the bottom of the list, it will have two purposes: one is to indicate when we're loading more data, but more importantly, when the loader is revealed (it appears on the visible part of the page), it will trigger the hx-get call to /tasks, passing the page number to be retrieved. The attribute next_page_number will also be provided by the context</p> <p>The directive hx-swap:outerHTML indicates that we will replace the outerHTML of this element with the set of <li>s we get from the server, which is great because not only we show the new data we got, but we also get rid of the loading icon. <p>We can now move to the views file.</p> <p>As a recap, here's how the GET /tasks view looks like by now; it's always returning the full template.<br> </p> <pre class="brush:php;toolbar:false">@require_http_methods(["GET", "POST"]) @login_required def tasks(request): if request.method == "POST": return _create_todo(request) # GET /tasks context = { "todos": request.user.todos.all().order_by("-created_at"), "fullname": request.user.get_full_name() or request.user.username, } return render(request, "tasks.html", context)
上面的程式碼已經做了改動,就是按照最新的待辦事項優先排序;既然我們期望有一個很長的列表,那麼在底部添加新項目並將其與無限滾動混合是沒有意義的- 新項目最終將混合在清單的中間。
我們現在需要區分常規 GET 請求和 HTMX 請求,為此我們將只傳回待辦事項清單和部分範本。有一個名為django-htmx 的函式庫,它非常方便,因為它使用request.htmx 等屬性和所有hx-* 屬性的值擴展了請求參數,但目前這有點過分了;現在讓我們檢查HTMX 標頭,並使用Django 分頁器處理分頁。
# core/views.py ... previous code PAGE_SIZE = 20 ...previous code @require_http_methods(["GET", "POST"]) @login_required def tasks(request): if request.method == "POST": return _create_todo(request) page_number = int(request.GET.get("page", 1)) all_todos = request.user.todos.all().order_by("-created_at") paginator = Paginator(all_todos, PAGE_SIZE) curr_page = paginator.get_page(page_number) context = { "todos": curr_page.object_list, "fullname": request.user.get_full_name() or request.user.username, "next_page_number": page_number + 1 if curr_page.has_next() else None, } template_name = "tasks.html" if "HX-Request" in request.headers: template_name += "#todo-items-partial" return render(request, template_name, context)
我們做的第一件事是檢查頁面參數,如果不存在則將其設為 1。
我們檢查請求中的 HX-Request 標頭,這將告知我們傳入的請求是否來自 HTMX,並讓我們相應地返回部分模板或完整模板。
這段程式碼肯定需要一些測試,但在此之前讓我們先嘗試一下。看看網路工具,當頁面滾動時如何觸發請求,直到到達最後一頁。您還可以看到動畫「正在載入」圖示短暫顯示;我已將網路速度限制為 4g,以使其可見時間更長。
添加測試
最後,我們可以新增一個測驗來確保分頁能如預期運作
<ul> <p>Soon we will get back to the template to add the hx-get ... hx-trigger="revealed" bit that performs the infinite scroll, but first let's just change the view to return several items instead of one on the toggle and create operations:<br> </p> <pre class="brush:php;toolbar:false">... previous code def _create_todo(request): title = request.POST.get("title") if not title: raise ValueError("Title is required") todo = Todo.objects.create(title=title, user=request.user) return render( request, "tasks.html#todo-items-partial", # <-- CHANGED {"todos": [todo]}, # <-- CHANGED status=HTTPStatus.CREATED, ) ... previous code @login_required @require_http_methods(["PUT"]) def toggle_todo(request, task_id): todo = request.user.todos.get(id=task_id) todo.is_completed = not todo.is_completed todo.save() return render( request, "tasks.html#todo-items-partial", # <-- CHANGED { "todos": [todo], # <-- CHANGED }, )
現在就這樣了!這是迄今為止我使用 HTMX 遇到的最有趣的事情。這篇文章的完整程式碼在這裡。
對於下一篇文章,我正在考慮使用 AlpineJS 新增一些客戶端狀態管理,或新增「截止日期」功能。再見!
以上是使用 HTMX 和 Django 建立待辦事項應用程序,部分無限滾動的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。Python以简洁和强大的生态系统著称,C 则以高性能和底层控制能力闻名。

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

Python在遊戲和GUI開發中表現出色。 1)遊戲開發使用Pygame,提供繪圖、音頻等功能,適合創建2D遊戲。 2)GUI開發可選擇Tkinter或PyQt,Tkinter簡單易用,PyQt功能豐富,適合專業開發。

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

要在有限的時間內最大化學習Python的效率,可以使用Python的datetime、time和schedule模塊。 1.datetime模塊用於記錄和規劃學習時間。 2.time模塊幫助設置學習和休息時間。 3.schedule模塊自動化安排每週學習任務。

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。
