Module:Auto parents

Module documentation[view] [edit] [history] [purge]

This module is used by the {{Auto parents}} template.

local p = {} --p stands for package

local getArgs = require('Module:Arguments').getArgs
local yesno = require('Module:Yesno')

--[=[
Return a formatted list of links referring to the parents of the current page

Parameters:
 * page: the page title to use, if not the current page name
 * display: an override display title to use for the top level.
 * no_links: if yes, do not link page titles
 * existing_links: if yes, check whether pages exist before making them links

Example:

 * page = A/B/C/D => [[A|A]], [[A/B|B]], [[A/B/C|C]]
 * page = A/B/C, display=Foo => [[A|Foo]], [[A/B|B]]
]=]
function p.parent_links( frame )
	local args = getArgs(frame)
	
	local no_links = yesno(args.no_links or args['no links'] or 'no')
	local existing_links = yesno(args.existing_links or args['existing links'] or 'no')
	
	local title
	
	-- select override page name if given
	if args['page'] ~= nil and args['page'] ~= "" then
		title = args['page']
	else
		title = mw.title.getCurrentTitle().prefixedText
	end
	-- the parts of the page title
    local parts = mw.text.split( title, "/", true )
    -- collected links for each parent
    local links = {}
	
    -- count forwards from the highest level to the second-lowest
    -- (the lowest level is the current page, not a parent)
    for level = 1, #parts -1, 1 do
    	
    	local link_name = parts[level]

    	-- at the top level, substitute the work display name if needed
    	if level == 1 and args['display'] ~= nil and args['display'] ~= "" then
    		link_name = args['display']
    	-- don't include namespace in link name
    	elseif level == 1 then
    		link_name = mw.title.getCurrentTitle().rootText
    	end
    	
    	local link_target = table.concat(parts, "/", 1, level)
		
        -- construct the link wikitext
        local link
        if no_links then
        	link = link_name
        elseif existing_links then
        	if mw.title.new(link_target).exists then
        		link = "[[" .. link_target .. "|" .. link_name .. "]]"
        	else
        		link = link_name
        	end
        else
    		link = "[[" .. link_target .. "|" .. link_name .. "]]"
    	end
    	
    	table.insert(links, link)
    end
	
    return table.concat(links, ", ")
end

return p