模組:沙盒/a2569875/wikidata utils

维基百科,自由的百科全书
文档图示 模块文档[创建]
local p={}
local lib_arg={}
--{{wikidata item | Q234 }}
function p.getEntityIdForTitle(input_title)
	if input_title == nil then return nil end
	local title = mw.title.new(input_title)
	if title == nil then return nil end
	local wikidata_item = ''
	mw.ustring.gsub(title:getContent() or "","%{%{%s*[Ww]ikidata%s*[Ii]tem%s*%|%s*([^%}%|%s]+)%s*[%}%|]",function(str) 
		wikidata_item = str or ''
		return str 
	end)
	mw.ustring.gsub(title:getContent() or "","%{%{%s*[Ww]ikidata%s*[Ii]tem%s*%|%s*1%s*=%s*([^%}%|%s]+)%s*[%}%|]",function(str) 
		wikidata_item = str or ''
		return str 
	end)
	if mw.text.trim(wikidata_item) == '' then
		wikidata_item = mw.wikibase.getEntityIdForTitle(input_title) or ''
	end
	if mw.text.trim(wikidata_item) == '' then
		wikidata_item = nil
	end
	return wikidata_item
end

function p.getEntityIdForCurrentPage()
	return p.getEntityIdForTitle(mw.title.getCurrentTitle().fullText)
end

function p.maketag(frame)
	-- For calling from #invoke. 
	local args, working_frame
	if frame == mw.getCurrentFrame() then
		-- We're being called via #invoke. The args are passed through to the module
		-- from the template page, so use the args that were passed into the template.
		if lib_arg.getArgs == nil then lib_arg = require('Module:Arguments') end
		args = lib_arg.getArgs(frame, {
			parentFirst=true
		}) --frame
	else
        -- We're being called from another module or from the debug console, so assume
        -- the args are passed in directly.
        args = frame
        if type(args) ~= type({}) then args = {frame} end
	end
	local value = args[1] or args['1']
	return'<span id="wikidata-item" data-wikidata-title="'..value..'"></span>'
end

return p