Module:Transclude random page

From the Audiovisual Identity Database, the motion graphics museum

Documentation for this module may be created at Module:Transclude random page/doc

local p = {}

local mRandom = require('Module:Random')
local currentTitle = mw.title.getCurrentTitle()

local function getRandomNumber(max)
    -- Gets a random integer between 1 and max; max defaults to 1
    return mRandom.number{max or 1}
end

local function expandArg(args, key)
    -- Emulate how unspecified template parameters appear in wikitext. If the
    -- specified argument exists, its value is returned, and if not the argument
    -- name is returned inside triple curly braces.
    local val = args[key]
    if val then
        return val
    else
        return string.format('{{{%s}}}', key)
    end
end

local function getPages(args)
    local pages = {}
    pages.root = args.rootpage or currentTitle.prefixedText
    pages.randompage = pages.root .. '/' .. expandArg(args, 'randompage')
    return pages
end

local function tryExpandTemplate(frame, title, args)
    local success, result = pcall(frame.expandTemplate, frame, {title = title, args = args})
    if success then
        return result
    else
        local msg = string.format(
            '<strong class="error">The page "[[%s]]" does not exist.</strong>',
            title
        )
        if mw.title.getCurrentTitle().namespace == 100 then -- is in the portal namespace
            msg = msg .. '[[Category:Portals needing attention]]'
        end
        return msg
    end
end

local function getRandomPageContent(frame, pages, num)
    return tryExpandTemplate(
        frame,
        pages.randompage .. '/' .. num
    )
end

function p._main(args, frame)
    frame = frame or mw.getCurrentFrame()
    local pages = getPages(args)
    local prefix = args.prefix or ''
    local max = args.max or 1

    local r = getRandomNumber(max)
    local num = ((r - 1) % max) + 1
    local ret = prefix .. getRandomPageContent(frame, pages, num)

    if args.more then
        ret = ret .. string.format('<div class="noprint" style="float: right;"><b>[[%s|%s]]</b></div>', pages.randompage, args.more)
    end
    if args.leftfooter then
        ret = ret .. string.format('<div class="noprint" style="float: left;">%s</div>', args.leftfooter)
    end
    if args.rightfooter then
        ret = ret .. string.format('<div class="noprint" style="float: right;">%s</div>', args.rightfooter)
    end

    return ret
end

local function makeInvokeFunction(func)
    return function (frame)
        local args = require('Module:Arguments').getArgs(frame, {
            trim = false,
            removeBlanks = false,
            wrappers = {
                'Template:Transclude random page', -- Change the template name here
            }
        })
        return func(args, frame)
    end
end

p.main = makeInvokeFunction(p._main)

return p
Cookies help us deliver our services. By using our services, you agree to our use of cookies.