跳转到内容

模組:TemplateExist

被永久保护的模块
维基百科,自由的百科全书

这是本页的一个历史版本,由A2569875留言 | 贡献2024年1月26日 (五) 08:18编辑。这可能和当前版本存在着巨大的差异。

local p = {}

function p.templateExist(input_data)
	local template_name = input_data
	local currentTitle = mw.title.getCurrentTitle()
	if type(input_data) == type({}) and type(input_data.args) == type({}) then
		template_name = input_data.args[1] or input_data.args['1'] or ''
		local page = input_data.args.page
		if mw.text.trim(page or '') ~= '' then
			local success, page_obj = pcall(mw.title.new, page)
			if success and type((page_obj or {}).getContent) == type(tostring) then
				currentTitle = page_obj
			end
		end
	end
	local template_title = p.getTemplateTitle(template_name)
	if 
		type((template_title or {}).getContent) == type(tostring) and
		type((currentTitle or {}).getContent) == type(tostring) 
	then
		local content = currentTitle:getContent()
		for capture in mw.ustring.gmatch(content, "%{%{%s*([^%{%}%|]+)%s*[%}%|]") do
			local check_template_name = mw.text.trim(capture or '')
			local check_template_title = p.getTemplateTitle(check_template_name)
			if mw.title.equals(check_template_title, template_title) then
				return true
			end
		end
	end
	return false
end

function p.getTemplateTitle(input_data)
	local template_name = input_data
	local is_lua = true
	if type(input_data) == type({}) and type(input_data.args) == type({}) then
		template_name = input_data.args[1] or input_data.args['1'] or ''
	end
	local function _return(_value)
		if is_lua then return _value
		else return _value and tostring(_value) or '' end
	end
	template_name = mw.text.trim(template_name or '')
	if template_name == '' then return _return() end
	local success, template_obj = pcall(mw.title.new, template_name, "Template")
	if not success then return _return() end
	local page_name = tostring(template_obj)
	local template_title = template_obj.redirectTarget or template_obj
	local redircct_name = tostring(template_title)
	if type(template_title.getContent) ~= type(tostring)then return _return() end
	if (template_title:getContent() or ''):len() > 0 then
		return _return(template_title)
	end
	local lib_zhcvt = require('Module:ZhConversion') --繁簡轉換
	for _, check_title in ipairs({
		lib_zhcvt.to_hant(page_name), lib_zhcvt.to_hans(page_name),
		lib_zhcvt.to_hant(redircct_name), lib_zhcvt.to_hans(redircct_name),
	}) do
		local _success, check_page = pcall(mw.title.new, check_title, "Template")
		if _success then
			check_page = check_page.redirectTarget or check_page
			return _return(check_page)
		end
	end
	return _return()
end
return p