[LUA] Article pagination method with lua

Share your ideas & teach other
Post Reply
jesuisnk
Posts: 14
Joined: Mon May 06, 2024 11:06 pm

[LUA] Article pagination method with lua

Post by jesuisnk »

DEMO:
Image

First, create file 'jesuisnk', with lua code:

Code: Select all

-- Slug
function slugVN(text)
    local diacriticsMap = {
        { base = 'a', regex = '[àáảãạăắằẵặẳâầấậẫẩ]' },
        { base = 'e', regex = '[èéẻẽẹêếềễệể]' },
        { base = 'i', regex = '[ìíỉĩị]' },
        { base = 'o', regex = '[òóỏõọôồốổỗộơờớởỡợ]' },
        { base = 'u', regex = '[ùúủũụưừứửữự]' },
        { base = 'y', regex = '[ỳýỷỹỵ]' },
        { base = 'd', regex = '[đ]' },
        { base = ' ', regex = '[%s]' }
    }

    local slug = text:lower()

    for _, diacritic in ipairs(diacriticsMap) do
        slug = slug:gsub(diacritic.regex, diacritic.base)
    end

    slug = slug:gsub('[%W_]+', '-') -- Remove any non-word characters
    slug = slug:gsub('[%s%-]+', '-') -- Replace whitespace and underscores with a single hyphen
    slug = slug:gsub('^%-+', '') -- Trim leading hyphens
    slug = slug:gsub('%-+$', '') -- Trim trailing hyphens

    return slug
end

-- BBcode and Smileys
local function smile(input_string)
    local arrEmoName = {'ami', 'anya', 'aru', 'aka', 'dauhanh', 'dora', 'le', 'menhera', 'moew', 'nam', 'pepe', 'qoobee', 'qoopepe', 'thobaymau', 'troll', 'dui', 'firefox', 'conan'}

    for _, emoName in ipairs(arrEmoName) do
        local pattern = ":" .. emoName .. "([0-9]*):"
        local replacement = '<img loading="lazy" src="https://dorew-site.github.io/assets/smileys/' .. emoName .. '/' .. emoName .. '%1.png" alt="%1"/>'
        input_string = input_string:gsub(pattern, replacement)
    end

    return input_string
end

local function bb_simple(input_string)
    local bbcode_rules = {
        { pattern = '%[b%](.-)%[/b%]', replacement = '<strong>%1</strong>' },
        { pattern = '%[i%](.-)%[/i%]', replacement = '<em>%1</em>' },
        { pattern = '%[u%](.-)%[/u%]', replacement = '<u>%1</u>' },
        { pattern = '%[s%](.-)%[/s%]', replacement = '<s>%1</s>' },
        { pattern = '%[url=(.-)%](.-)%[/url%]', replacement = '<a href="%1">%2</a>' },
        { pattern = '%[img%](.-)%[/img%]', replacement = '<img src="%1" />' },
        -- Add more rules for other BBCode tags as needed
    }

    for _, rule in ipairs(bbcode_rules) do
        input_string = input_string:gsub(rule.pattern, rule.replacement)
    end

    return input_string
end

function bbcode(nd)
    nd = nd:gsub('(\r\n|\r|\n)', '<br>')
    nd = smile(nd)
    nd = bb_simple(nd)
    return nd
end

-- PAGINATION
function paging(trang, p, max)
    local output = ""
    if max > 1 then
        output = output .. "<center><div class=\"topmenu pagination\">"
        local a = ' <a class="pagenav" href="/' .. trang .. ''
        if p > max then
            p = max
        end
        if p > 1 then
            output = output .. (a .. p - 1 .. '">«</a>')
        end
        if p > 3 then
            output = output .. (a .. '1">1</a>')
        end
        if p > 4 then
            output = output .. '<span>...</span>'
        end
        if p > 2 then
            output = output .. (a .. p - 2 .. '">' .. p - 2 .. '</a>')
        end
        if p > 1 then
            output = output .. (a .. p - 1 .. '">' .. p - 1 .. '</a>')
        end
        output = output .. '<span class="current"><b>' .. p .. '</b></span>'
        if p < max - 1 then
            output = output .. (a .. p + 1 .. '">' .. p + 1 .. '</a>')
        end
        if p < max - 2 then
            output = output .. (a .. p + 2 .. '">' .. p + 2 .. '</a>')
        end
        if p < max - 3 then
            output = output .. '<span>...</span>'
        end
        if p < max then
            output = output .. (a .. max .. '" class="next">' .. max .. '</a>')
        end
        if p < max then
            output = output .. (a .. p + 1 .. '">»</a>')
        end
        output = output .. "</div></center>"
    end
    return output
end
Then, at 'index' file, paste lua code:

Code: Select all

include('jesuisnk')

print([[<div class="phdr"><i class="fa fa-th-list" style="color:yellow;"></i> <h2>Bài Viết Mới</h2></a></div>]])
local post_check, post_check_list, post_check_stats = api.post_info()
post_total = tonumber(post_check_stats['total'])
per = 2
page_max = math.floor(post_total / per)
if post_total % per ~= 0 then
    page_max = page_max + 1
end
p = tonumber(req.get.page) or 1
if p < 1 then
    p = 1
end
if p > page_max then
    p = page_max
end
st = p * per - per

function slice(tbl, first, last, step)
    local sliced = {}
    for i = first or 1, last or #tbl, step or 1 do
        sliced[#sliced + 1] = tbl[i]
    end
    return sliced
end

local post_check1, post_list, post_stats = api.post_info({limit=post_total})
--table.insert(post_list,1,post_list[0])
if post_total > 0 then
    for loopindex, article in ipairs(slice(post_list,st,st+per-1)) do
        thumbnail = string.match(article['content'], "%[img%](.-)%[/img%]") or 'https://i.imgur.com/01T3Bxl.png'
        colors = {'red', 'blue', 'green', 'orange'}
        randomIndex = math.random(1, #colors)
        randomColor = colors[randomIndex]
        topicClass = "cat_"..randomColor
        category = article['ForumInfo']
        link = "/article/"..article['id'].."-"..slugVN(article['title'])..".html"
        local html = [[
            <div class="list">
                <div style="float:left">
                    <img src="]]..thumbnail..[[" title="]]..article['title']..[[" alt="]]..article['title']..[[" width="55" height="55" class="thumbnail"/>
                </div>
                <a href="]]..link..[["><b>]]..article['title']..[[</b></a><br/>
                <b>Thể loại:</b> <span class="mau topic ]]..topicClass..[[">]]..category['name']..[[</span><br/>
                <b>Đăng:</b> ]]..article['date']..[[
            </div>
        ]]
        print(html)
    end
    print(paging('?page=',p,page_max))
else
    print([[<div class="list1">Chưa có bài viết nào!</div>]])
end
Last edited by jesuisnk on Thu May 09, 2024 12:23 am, edited 2 times in total.
jesuisnk
Posts: 14
Joined: Mon May 06, 2024 11:06 pm

Re: [LUA] Article pagination method with LUA

Post by jesuisnk »

- Let me explain a little about the above code. I intentionally wrote loops to cut the multidimensional array into pieces with the number of pages received from the request as follows:

Code: Select all

local post_check, post_check_list, post_check_stats = api.post_info()
post_total = tonumber(post_check_stats['total'])
per = 2
page_max = math.floor(post_total / per)
if post_total % per ~= 0 then
    page_max = page_max + 1
end
p = tonumber(req.get.page) or 1
if p < 1 then
    p = 1
end
if p > page_max then
    p = page_max
end
st = p * per - per
Last edited by jesuisnk on Thu May 09, 2024 12:24 am, edited 1 time in total.
jesuisnk
Posts: 14
Joined: Mon May 06, 2024 11:06 pm

Re: [LUA] Article pagination method with LUA

Post by jesuisnk »

Then I tried passing OFFSET to api.post_info(), but it failed. So I, created a function that works similar to LIMIT and OFFSET like SQL. This will affect the performance of the site, because of too many loops, but it's still good if your 'index' doesn't have too many loops.

Code: Select all

function slice(tbl, first, last, step)
    local sliced = {}
    for i = first or 1, last or #tbl, step or 1 do
        sliced[#sliced + 1] = tbl[i]
    end
    return sliced
end
USAGE:

Code: Select all

for loopindex, article in ipairs(slice(post_list,st,st+per-1)) do
-- anything
end
User avatar
Xkria-uy
Posts: 122
Joined: Fri Apr 07, 2023 9:27 pm
Location: Uruguay
Contact:

Re: [LUA] Article pagination method with lua

Post by Xkria-uy »

...
...
AddText_05-10-05.53.33.jpg (187.9 KiB) Viewed 23223 times
jesuisnk
Posts: 14
Joined: Mon May 06, 2024 11:06 pm

Re: [LUA] Article pagination method with lua

Post by jesuisnk »

Xkria-uy wrote: Fri May 10, 2024 8:54 am AddText_05-10-05.53.33.jpg
You can run a loop yourself that includes posts that don't belong to the "chat" category for the above case
Post Reply