模块:TemplateArgSpreader

来自维阿百科
跳转至: 导航搜索

此模块的文档可以在模块:TemplateArgSpreader/doc创建

local module = {}

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

function _main(args)
	local templateTitle = args['__tl']
	local templateArgs = mw.text.jsonDecode(args['__args'] or '{}')
	if mw.title.new(templateTitle, 'Template') == nil then error('模板“'..titleTemplate..'”不存在!') end
	
	args['__tl'] = nil
	args['__args'] = nil
	
	for k, v in pairs(args) do
		local argValue = v
		
		if templateArgs[k] ~= nil then
			local tlArgBlendMode = templateArgs[k].blendMode
			local tlArgVal = templateArgs[k].value
			
			if tlArgBlendMode == 'begin' then
				argValue = v..tlArgVal
			elseif tlArgBlendMode == 'end' then
				argValue = tlArgVal..v
			elseif tlArgBlendMode == 'middle' then
				argValue = mw.ustring.gsub(tlArgVal, '%${__arg}', v)
			end
		end
		
		templateArgs[k] = argValue
	end
	
	for k, v in pairs(templateArgs) do
		if type(v) == 'table' then
			templateArgs[k] = templateArgs[k].value
		end
	end
	
	return mw.getCurrentFrame():expandTemplate{ title = templateTitle, args = templateArgs }
end

function _stringify(args)
	local blendModesStr = args['__blendModes'] or ''

	local blendModes = {}
	if #blendModesStr ~= 0 then
		for v in mw.text.gsplit(blendModesStr, ',', true) do
			local mode = mw.text.split(v, ':', true)
			blendModes[mw.text.trim(mode[1])] = mw.text.trim(mode[2])
		end
	end
	
	args['__blendModes'] = nil
	
	local templateArgs = {}
	for k, v in pairs(args) do
		if k:find('^%d+$') then error('不能出现匿名(数字)参数!') end
		templateArgs[k] = {
			value = v,
			blendMode = blendModes[k] or 'rewrite'
		}
	end

	return mw.text.jsonEncode(templateArgs)
end

function module.main(frame)
	local args = getArgs(frame)
	return _main(args)
end

function module.stringify(frame)
	local args = getArgs(frame)
	return _stringify(args)
end

return module