Hey!
Since this blogpost was written, I created a new and improved way to do infinite scrolling. Check out the YouTube Video to see the implementation.
Legacy Implementation
Htmx superpowers your html, allowing it to do things you would typically have to do in JavaScript. After discovering issues with duplicate pages due to my pagination implementation, I removed all the duplication with infinite scroll!
Luckily, I came across an excellent youtube video by bugBytes who walks you through how to pull off infinite scroll with htmx.
I won't bore you with all the details, but I will highlight how I adjusted the implementation to handle category pages.
In bugByte's example, he hardcodes the URL to fetch articles since he is only working with one view:
<div hx-get="{% film-list %}?page={{ page_obj.number|add:1 }}" hx-trigger="revealed" hx-swap="afterend" hx-target="this">
In my case, posts can come from multiple views. I modified the request to reference a url
variable I passed within the view to support more than one view. Notice I replace film-list
with url
.
<div hx-get="{{ url }}?page={{ page_obj.number|add:1 }}" hx-trigger="revealed" hx-swap="afterend" hx-target="this">
Within each view, I pass the current path into the template as a context variable:
class CategoryView(ListView):
...
def get_context_data(self, *args, **kwargs):
...
context["url"] = self.request.path
return context
This way, the template is always fetching the correct url!
Conclusion
After running into issues with duplicate content with my previous pagination implementation, I decided to use htmx to implement infinite scrolling. This resolved the duplication issue and introduced new functionality. I call that a win!