Jump to content

Module:Parameter names example/sandbox

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Mr. Stradivarius (talk | contribs) at 10:34, 29 August 2014 (create an automatic template invocation). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
-- This module implements {{parameter names example}}.

local p = {}

local function makeParam(s)
	local lb = '{'
	local rb = '}'
	return lb:rep(3) .. s .. rb:rep(3)
end

local function italicize(s)
	return "''" .. s .. "''"
end

function p._main(args, frame)
	frame = frame or mw.getCurrentFrame()

	-- Find how we want to format the arguments to the template.
	local formatFunc
	if args._display == 'italics' or args._display == 'italic' then
		formatFunc = italicize
	else
		formatFunc = makeParam
	end

	-- Build the table of template arguments.
	local targs = {}
	for k, v in pairs(args) do
		if type(k) == 'number' then
			targs[v] = formatFunc(v)
		elseif not k:find('^_') then
			targs[k] = v
		end
	end

	-- Find the template name.
	local templateName
	if args._template then
		templateName = args._template
	else
		-- Find the title object for the template.
		local templateTitle
		local currentTitle = mw.title.getCurrentTitle()
		if currentTitle.prefixedText:find('/sandbox$') then
			templateTitle = currentTitle
		else
			templateTitle = currentTitle.basePageTitle
		end

		-- Format the template name according to the namespace we are in.
		if templateTitle.namespace == 10 then -- NS_TEMPLATE
			templateName = templateTitle.text
		elseif templateTitle.namespace == 0 then -- NS_MAIN
			templateName = ':' .. templateTitle.text
		else
			templateName = templateTitle.prefixedText
		end
	end

	local ret = ''

	-- Build the template invocation.
	if args._code then
		local codeArgs = {}
		for k, v in pairs(targs) do
			codeArgs[k] = v
		end
		local code = { templateName }
		for k, v in ipairs(codeArgs) do
			if v:find('=', 1, true) then
				-- Something like 1=foo=bar; we need to do it as a named arg.
				break
			end
			code[#code + 1] = v
			codeArgs[k] = nil
		end
		for k, v in pairs(codeArgs) do
			code[#code + 1] = k .. '=' .. v
		end
		code = '{{' .. table.concat(code, '|') .. '}}'
		code = '<pre style="white-space: pre-wrap;">' .. code .. '</pre>\n\n'
		ret = ret .. frame:preprocess(code)
	end

	-- Call the template with the arguments.
	local success, result = pcall(
		frame.expandTemplate,
		frame,
		{title = templateName, args = targs}
	)
	if success then
		ret = ret .. result
	end

	return ret
end

function p.main(frame)
	local args = require('Module:Arguments').getArgs(frame, {
		wrappers = 'Template:Parameter names example'
	})
	return p._main(args, frame)
end

return p