Module:Template link

From Rhythm Heaven Wiki
Revision as of 08:35, 3 August 2025 by HyperNervie (talk | contribs) (Created page with "local p = {} local function trim(str) if str == nil then return nil end return mw.text.trim(tostring(str)) end function p.main(frame) local args = {} for k, v in pairs(frame.args) do args[k] = v end for k, v in pairs(frame:getParent().args) do args[k] = v end return p.makeLink(args) end function p.makeLink(args) local templateName = trim(args[1]) if templateName == nil then error("Template name not given") end...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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

local p = {}

local function trim(str)
    if str == nil then return nil end
    return mw.text.trim(tostring(str))
end

function p.main(frame)
    local args = {}
    for k, v in pairs(frame.args) do
        args[k] = v
    end
    for k, v in pairs(frame:getParent().args) do
        args[k] = v
    end
    return p.makeLink(args)
end

function p.makeLink(args)
	local templateName = trim(args[1])
	if templateName == nil then
		error("Template name not given")
	end

    local linkedTitle = mw.title.new(templateName, "Template")
    if linkedTitle == nil then
        error(mw.ustring.format([["%s" isn't a valid title]], templateName))
    end

    local slash = mw.ustring.sub(templateName, 1, 1) == "/"
    if slash then
        linkedTitle = mw.title.new(templateName)
    end

    local titleText = linkedTitle.fullText
    local linkText = linkedTitle.text
    if slash then
        -- Do nothing
    elseif linkedTitle.nsText == "" then
        titleText = ":" .. titleText
        linkText = ":" .. linkText
    elseif linkedTitle.nsText ~= "Template" then
        linkText = linkedTitle.prefixedText
    end

    local templateArgs = ""
    if args[2] ~= nil then
        templateArgs = "|" .. tostring(templateArgs)
    end

    local inCode = trim(args.code)
    local output = mw.ustring.format("{{[[%s|%s]]%s}}", titleText, linkText, templateArgs)
    if inCode ~= nil and inCode ~= "" then
        output = mw.ustring.format("<code>%s</code>", output)
    end

    return output
end

return p