Jump to content

Module:Template link with magic

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Mr. Stradivarius (talk | contribs) at 17:01, 12 January 2014 (start a replacement for Template:Tlx, Template:Tlu and other template-linking templates). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

-- This module implements template link templates like {{tlx}}, {{tlu}} and {{tlp}} that take many parameters.
-- The module attempts to display named parameters as best it can, although the order will not be preserved.
-- Templates that take only one or two parameters, such as {{tl}}, are not implemented, as they will give
-- better performance as regular templates.

local getArgs = require('Module:Arguments').getArgs

local p = {}

local function makeInvokeFunction(funcName)
	return function (frame)
		local args = getArgs(frame, {trim = false, removeBlanks = false})
		return p[funcName](args)
	end
end

function p.constructInvocation(targs, data)
	-- Builds a template invocation from the template args (targs).
	-- The algorithm is a modified version of the one used in [[Module:Unsubst]].
	
	local nowiki = mw.text.nowiki -- If this is used we will call it for every argument, so making it local to improve performance.

	local cleanVal
	if data.nowiki then
		cleanVal = function (v)
			return nowiki(v)
		end
	else
		cleanVal = function (v)
			return v
		end
	end

	-- Define the most common escaped characters.
	local pipe = '|'
	local equals = '='
	local leftBrackets = '{{'
	local rightBrackets = '}}'

	-- Work out what the template link should be.
	local template = data.template
	if not template then
		error('Template name not specified', 2)
	end
	if data.link then
		template = mw.ustring.format('[[Template:%s|%s]]', template, template)
	end

	-- Process numbered args.
	local ret = leftBrackets .. template
	for k, v in ipairs(targs) do
		if string.find(v, '=', 1, true) then
			-- Likely something like 1=foo=bar, so we need to do it as a named arg.
			break
		end
		ret = ret .. pipe .. cleanVal(v)
		targs[k] = nil
	end

	-- Process named args.
	for k, v in pairs( targs ) do
		ret = ret .. pipe .. cleanVal(k) .. equals .. cleanVal(v)
	end

	return ret .. rightBrackets
end

return p