Module:utilities/format categories with sort keys

From Linguifex
< Module:utilities
Revision as of 09:32, 31 July 2024 by Sware (talk | contribs) (Created page with "local data = mw.loadData("Module:utilities/format_categories/data") --[[ Format the categories with the appropriate sort key, which may be specified individually per category. CATEGORIES is a list of objects as follows: { category = "Category name", sort_key = "Sort key" or nil } The individual sort_key values are treated as individual SORT_KEY values for only that specific category. ]] -- Otherwise this function behaves like format_categories in Module:utilities....")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Documentation for this module may be created at Module:utilities/format categories with sort keys/doc

local data = mw.loadData("Module:utilities/format_categories/data")

--[[
Format the categories with the appropriate sort key, which may be specified
individually per category. CATEGORIES is a list of objects as follows:
{
	category = "Category name",
	sort_key = "Sort key" or nil
}
The individual sort_key values are treated as individual SORT_KEY values for
only that specific category.
]]
-- Otherwise this function behaves like format_categories in [[Module:utilities]].
return function(categories, lang, sort_key, sort_base, force_output, sc)
	if type(lang) == "table" and not lang.getCode then
		error("The second argument to format_categories_with_sort_keys should be a language object.")
	end

	local title_obj = mw.title.getCurrentTitle()	

	if force_output or data.allowedNamespaces[title_obj.nsText] or data.allowedPrefixedPages[title_obj.prefixedText] then
		local PAGENAME = mw.loadData("Module:headword/data").pagename
		
		if not lang then
			lang = require("Module:languages").getByCode("und")
		end
		
		-- Generate a default sort key
		sort_base = lang:makeSortKey(sort_base or PAGENAME, sc)
		
		if not sort_key or sort_key == "" then
			sort_key = sort_base
		end
		
		-- If the sortkey is empty, remove it.
		if sort_key == "" then
			sort_key = nil
		end
		
		local out_categories = {}
		for key, cat in ipairs(categories) do
			local individual_sort_key = cat.sort_key or sort_key
			if individual_sort_key == "" then individual_sort_key = " " end
			out_categories[key] = "[[Category:" .. cat.category .. (individual_sort_key and "|" .. individual_sort_key or "") .. "]]"
		end
		
		return table.concat(out_categories, "")
	else
		return ""
	end
end