Module:BCIChapterList: Difference between revisions

From Candypedia
Module to make a user readable table
 
m typo!
Line 11: Line 11:


function p.renderTable(frame)
function p.renderTable(frame)
     -- 1) grab the raw wikitext of Template:BCIChaptersList
     -- 1) grab the raw wikitext of Template:BCIChapterList
     local tpl = mw.title.new("Template:BCIChaptersList")
     local tpl = mw.title.new("Template:BCIChapterList")
     local raw = tpl and tpl:getContent() or ""
     local raw = tpl and tpl:getContent() or ""



Revision as of 23:54, 23 April 2025

Documentation for this module may be created at Module:BCIChapterList/doc

-- Module:BCIChapterList
local p = {}

-- helper: format ISO date YYYY-MM-DD → M/D/YY
local function formatDate(iso)
    local y,m,d = iso:match("^(%d%d%d%d)%-(%d%d)%-(%d%d)$")
    if not y then return iso end
    m = tonumber(m); d = tonumber(d)
    return m .. "/" .. d .. "/" .. y:sub(3,4)
end

function p.renderTable(frame)
    -- 1) grab the raw wikitext of Template:BCIChapterList
    local tpl = mw.title.new("Template:BCIChapterList")
    local raw = tpl and tpl:getContent() or ""

    -- 2) parse out each {{BCIChapter|…}} and collect rows
    local rows = {}
    for line in raw:gmatch("[^\r\n]+") do
        line = mw.text.trim(line)
        if line:find("^{{BCIChapter") then
            -- extract inner params
            local inner = line:match("^{{BCIChapter%s*(.+)}}$")
            if inner then
                -- strip leading pipe if present
                if inner:sub(1,1) == "|" then inner = inner:sub(2) end
                -- build a map of k → v
                local params = {}
                for part in inner:gmatch("[^|]+") do
                    local k,v = part:match("^(%w+)%s*=%s*(.+)$")
                    if k and v then params[k] = v end
                end
                if params.title and params.date then
                    table.insert(rows, {
                        title = params.title,
                        date  = params.date,
                        seq   = tonumber(params.seq) or 0
                    })
                end
            end
        end
    end

    -- 3) sort by seq ascending, just in case
    table.sort(rows, function(a,b) return a.seq < b.seq end)

    -- 4) build the wikitable
    local out = {
      '{| class="wikitable sortable"',
      '! Title',
      '! Published'
    }
    for _, r in ipairs(rows) do
        table.insert(out, "|-")
        table.insert(out,
          "| [[" .. r.title .. "]] || " .. formatDate(r.date)
        )
    end
    table.insert(out, "|}")
    return table.concat(out, "\n")
end

return p