模块:TemplateDemo:修订间差异

来自「荏苒之境」
无编辑摘要
无编辑摘要
第42行: 第42行:
local template_data = parse_template_data("Template:"..template_name)
local template_data = parse_template_data("Template:"..template_name)
local newline = not (template_data and template_data.format ~= "inline")
local newline = not (template_data == nil or template_data.format ~= "inline")
local args = frame:getParent().args
local args = frame:getParent().args

2025年8月11日 (一) 19:31的版本

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

local utils_str = require("Module:Utils/String")

local html = mw.html

local template_demo = {}

local function parse_template_data(title)
	local content = mw.title.new(title).content
	local raw = utils_str.match_xml_noattr(content, "templatedata")
	if raw == nil then
		return nil
	end
	local succ, res = pcall(mw.text.jsonDecode, raw)
	return succ and res or nil
end

local function append_argument(t, k, v, newline, last_num_param)
	local k_num = tonumber(k)
	if k_num == 1 then
		return 1
	end
	t[#t+1] = "| "
	if k_num == nil or last_num_param ~= k_num - 1 then
		t[#t+1] = k_num and tostring(k_num - 1) or k
		t[#t+1] = " = "
	end
	t[#t+1] = utils_str.trim(v)
	if newline then
		t[#t+1] = "\n"
	end
	return k_num
end

template_demo.show = function(frame)
	local args = frame.args
	local template_name = args[1]

	if template_name == nil or template_name == '' then
		return html.create("p"):addClass("error")
			:wikitext("没有指定模板名!")
	end
	
	local template_data = parse_template_data("Template:"..template_name)
	local newline = not (template_data == nil or template_data.format ~= "inline")
	local args = frame:getParent().args
	
	local t = {"{{", utils_str.trim(template_name), "\n"}
	local last_num_param = 1
	local has_arg
	
	if template_data ~= nil and type(template_data.paramOrder) == "table" then
		local order = template_data.paramOrder
		local appended = {}
		for i = 1, #order do
			local k = order[i]
			local k_num = tonumber(k)
			k = k_num and k_num + 1 or k
			local v = args[k]
			if v ~= nil then
				last_num_param = append_argument(t, k, v, newline, last_num_param)
			end
			appended[k] = true
		end
		for k, v in pairs(args) do
			if appended[k] == nil then
				last_num_param = append_argument(t, k, v, newline, last_num_param)
			end
		end
	else
		for k, v in pairs(args) do
			last_num_param = append_argument(t, k, v, newline, last_num_param)
		end
	end
	
	if last_num_param ~= 1 then
		t[#t+1] = "}}"
	else
		t[#t] = "}}"
	end
	
	local source = table.concat(t)
	return frame:preprocess(source).."\n\n示例代码:\n"..
		frame:extensionTag("syntaxhighlight", source, { lang = "wikitext" })
end

return template_demo