Module:Archive list entries

From the Tesseract Wiki, the wiki for all things Marvel Cinematic Universe
Jump to navigation Jump to search
Module documentation
This documentation is transcluded from Module:Archive list entries/doc. [edit] [history] [purge]
Module:Archive list entries's function main is invoked by Template:Archive list.
Function list
L 4 — p.main

This module serves as a wrapper around the DPL search that populates the {{Archive list}} template with links to each archived page. It is used to efficiently search (in a single query) and sort (using a "natural" sort, where "Archive 10" does not come between "Archive 1" and "Archive 2").


-- <nowiki>
local p = {}

function p.main(frame)
	local title = mw.title.getCurrentTitle()
	local searchPrefix = title.text
	local links = {}
	local SEPARATOR = "§-§"

	if title.subpageText:find( "^[Aa]rchive" ) then
		searchPrefix = title.baseText
	end
	
	local results = frame:callParserFunction( "#dpl", {
		"",
		namespace = title.nsText,
		skipthispage = "no",
		titlematch = searchPrefix .. "/Archive %|" .. searchPrefix .. "/archive %",
		format = ",%PAGE%" .. SEPARATOR
	})

	if results then
		local numOffset = #( searchPrefix .. "/Archive " ) + 1
		if title.nsText ~= "" then
			numOffset = numOffset + #( title.nsText .. ":" )
		end
		
		results = mw.text.split( results, SEPARATOR, true )
		table.remove( results ) -- empty result after ending separator
		table.sort( results, function( a, b )
			a = tonumber( a:sub( numOffset ) ) or 0
			b = tonumber( b:sub( numOffset ) ) or 0
			return a < b
		end )
		
		for _, v in ipairs( results ) do
			-- only link to result if a number follows "Archive " in its name
			-- this mirrors the previous titleregexp behaviour from {{Archive list}}
			if tonumber( v:sub( numOffset ) ) then
				table.insert( links, string.format( "[[%s|%s]]", v, v:sub( numOffset ) ) )
			end
		end
	end
	
	return table.concat( links, " '''&bull;''' " )
end

return p