Module:Template invocation

Revision as of 15:35, 23 November 2014 by wikipedia>Mr. Stradivarius (escape the equals sign as well)

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

-- This module makes a template invocation from a template name and a table
-- of arguments.

local p = {}

function p.invocation(name, args, format)
	-- Copy the invocation args and convert magic words.
	-- We need to make a copy of the table rather than just using the original,
	-- as some of the values may be erased when building the invocation.
	local invArgs = {}
	for k, v in pairs(args) do
		invArgs[k] = v
	end

	-- Get the separators to use.
	local seps = {
		openb = '{{',
		closeb = '}}',
		pipe = '|',
		equals = '='
	}
	if format == 'nowiki' then
		for k, v in pairs(seps) do
			seps[k] = mw.text.nowiki(v)
		end
	end

	-- Build the invocation body with numbered args first, then named.
	local ret = {}
	ret[#ret + 1] = seps.openb
	ret[#ret + 1] = name
	for k, v in ipairs(invArgs) do
		if v:find('=', 1, true) then
			-- Likely something like 1=foo=bar, we need to do it as a named arg
			break
		end
		ret[#ret + 1] = seps.pipe
		ret[#ret + 1] = v
		invArgs[k] = nil -- Erase the key so that we don't add the value twice
	end
	for k, v in pairs(invArgs) do
		ret[#ret + 1] = seps.pipe
		ret[#ret + 1] = k
		ret[#ret + 1] = seps.equals
		ret[#ret + 1] = v
	end
	ret[#ret + 1] = seps.closeb

	return table.concat(ret)
end

return p