Module:RelatedCategories

From SW420
Jump to navigation Jump to search

Documentation for this module may be created at Module:RelatedCategories/doc

local function exists(page)
	local success, title = pcall(mw.title.new, page)
	return success and title and title.exists or false
end

local p = {}

function p._main(args)
	local cats = {}
	local num = 0
	local result = ''

	for k, v in pairs(args) do
		local param = v:gsub("[%[%]]*", "")
		if param:find("Category:") then
			if exists(param) then
				local page = param:gsub("Category:", "")
				table.insert(cats, page)
				num = num + 1
			end
		end
	end
	
	if num ~= 0 then
		local catlist = {}
		for x, r in pairs(cats) do
			table.insert(catlist, string.format('<li class="category">[[:Category:%s|%s]]</li>', r, r))
		end
		
		table.insert(catlist, 1, '<div id="related-catlinks" class="related-catlinks">Related Categories: <ul id="rel-catlist" class="categories">')
		table.insert(catlist, '</ul><div>')
		result = table.concat(catlist)
	end
	
	return result
end
	
function p.main(frame)
	local args = {}
	for k, v in pairs(frame:getParent().args) do
		v = v:match('^%s*(.-)%s*$')
		if v ~= '' then
			args[k] = v
		end
	end
	return p._main(args)
end

return p