Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Module:CategoryTranscluder

From Teriock
Revision as of 11:26, 14 January 2025 by Gpe (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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

local p = {}

-- Helper function to get all pages in a category
local function getPagesInCategory(categoryName)
    -- Remove "Category:" prefix if present
    categoryName = categoryName:gsub('^[Cc]ategory:', '')
    
    local pages = {}
    local category = mw.site.categories[categoryName]
    
    if not category then
        return pages
    end
    
    -- Iterate through all pages in the category
    for title in category:pages() do
        table.insert(pages, title.prefixedText)
    end
    
    -- Sort pages alphabetically
    table.sort(pages)
    
    return pages
end

-- Main function to transclude all pages in a category
function p.transcludeCategory(frame)
    local categoryName = frame.args[1]
    
    if not categoryName then
        return '<strong class="error">Error: Category name not provided</strong>'
    end
    
    local pages = getPagesInCategory(categoryName)
    
    if #pages == 0 then
        return string.format('<strong class="error">Error: No pages found in category "%s"</strong>', categoryName)
    end
    
    -- Build the output with transclusions
    local output = {}
    for _, pageName in ipairs(pages) do
        -- Skip the category page itself
        if not pageName:match('^[Cc]ategory:') then
            table.insert(output, string.format('{{:%s}}', pageName))
        end
    end
    
    -- Join all transclusions with newlines
    return table.concat(output, '\n')
end

-- Function to get a simple list of pages without transclusion
function p.listPages(frame)
    local categoryName = frame.args[1]
    
    if not categoryName then
        return '<strong class="error">Error: Category name not provided</strong>'
    end
    
    local pages = getPagesInCategory(categoryName)
    
    if #pages == 0 then
        return string.format('<strong class="error">Error: No pages found in category "%s"</strong>', categoryName)
    end
    
    -- Build the output as a bullet list
    local output = {}
    for _, pageName in ipairs(pages) do
        if not pageName:match('^[Cc]ategory:') then
            table.insert(output, string.format('* [[%s]]', pageName))
        end
    end
    
    return table.concat(output, '\n')
end

return p