From 6181701da6192024e99a1f5d41abdecdbb9b64ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lera=20Elvo=C3=A9?= Date: Mon, 19 May 2025 09:33:30 +0300 Subject: [PATCH] add offset pagination and permalinking to posts --- apps/threads.lua | 11 ++++++----- views/threads/thread.etlua | 15 ++++++++++----- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/apps/threads.lua b/apps/threads.lua index dca112a..89b76fb 100644 --- a/apps/threads.lua +++ b/apps/threads.lua @@ -57,6 +57,7 @@ app:post("thread_create", "/create", function(self) end) app:get("thread", "/:slug", function(self) + local posts_per_page = 10 local thread = Threads:find({ slug = self.params.slug }) @@ -67,7 +68,8 @@ app:get("thread", "/:slug", function(self) local post_count = Posts:count(db.clause({ thread_id = thread.id })) - local pages = math.floor(post_count / 20) + self.pages = math.ceil(post_count / posts_per_page) + self.page = tonumber(self.params.page) or 1 local posts = db.query([[ SELECT posts.id, post_history.content, users.username, avatars.file_path AS avatar_path @@ -80,15 +82,14 @@ app:get("thread", "/:slug", function(self) LEFT JOIN avatars ON users.avatar_id = avatars.id WHERE - posts.thread_id = ? and posts.id > ? + posts.thread_id = ? ORDER BY posts.created_at ASC - LIMIT 20 - ]], thread.id, tonumber(self.params.cursor or 0)) + LIMIT 20 OFFSET ? + ]], thread.id, (self.page - 1) * posts_per_page) self.topic = Topics:find(thread.topic_id) self.user = util.get_logged_in_user_or_transient(self) self.posts = posts - self.next_cursor = #posts > 0 and posts[#posts].id or nil return {render = "threads.thread"} end) diff --git a/views/threads/thread.etlua b/views/threads/thread.etlua index 72acfc3..d583ff5 100644 --- a/views/threads/thread.etlua +++ b/views/threads/thread.etlua @@ -1,10 +1,11 @@

<%= thread.title %>

Posted under "><%= topic.name %> <% for _, post in ipairs(posts) do %> -

+
">
"><%= post.username %>

<%- post.content %>

+ permalink
<% end %> @@ -15,8 +16,12 @@ <% end %> -<% if next_cursor then %> - - Older posts → - + +<% for i = 1, math.max(pages, 1) do %> + <% if i == page then %> + <%= tostring(i)%> + <% else %> + <%= tostring(i)%> + <% end %> <% end %> +