Module:Template link

Revision as of 10:18, 3 August 2025 by HyperNervie (talk | contribs) (More flags)

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

local function yes(str)
	if str == nil or str == false then return false end
	if type(str) ~= "string" then return true end
	return mw.text.trim(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 subst
	if mw.ustring.sub(templateName, 1, 6) == "subst:" then
		subst = "subst"
		templateName = mw.ustring.sub(templateName, 7)
	elseif mw.ustring.sub(templateName, 1, 10) == "safesubst:" then
		subst = "safesubst"
		templateName = mw.ustring.sub(templateName, 11)
	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 output
	if yes(args.nolink) then output = linkText
	else output = mw.ustring.format("[[%s|%s]]", titleText, linkText) end

	if subst ~= nil then
		if yes(args.substhelp) then
			subst = "[[mw:Help:Substitution|" .. subst .. "]]"
		end
		output = subst .. ":" .. output
	end

	if args[2] ~= nil then
		output = output .. "|" .. tostring(args[2])
	end
	output = "{{" .. output .. "}}"

	local html
    if yes(args.code) then
		html = mw.html.create("code")
	elseif yes(args.mono) then
		html = mw.html.create("span"):css("font-family", "monospace")
    end
	if yes(args.nowrap) then
		if html == nil then html = mw.html.create("span") end
		html:css("white-space", "nowrap")
	end
	if html ~= nil then
		output = tostring(html:wikitext(output))
	end

    return output
end

return p