Documentation for this module may be created at Module:Parent/Documentation
local p = {}
-- returns a sequence of all headings in title
function headingList( title )
-- insert leading newline to make our pattern simpler
local content = "\n" .. title:getContent()
local names = {}
for level, name in string.gmatch( content, "\n(=+)%s*([^\n][^\n]-)%s*%1\n" ) do
table.insert( names, name )
end
return names
end
--[[
Checks if the enclosing page has the given section. This executes on the
top-level page being processed, not the template containing the invoke call.
Usage: {{#invoke:parent|ifSection|section|then|else}}
Arguments:
section - the section name to check for (Required)
then - text to display if the page has the section (Optional)
else - text to display if the page does not have the section (Optional)
]]
function p.ifSection( frame )
local title = mw.title.getCurrentTitle()
local heading = frame.args[1]
if not heading or string.len( heading ) == 0 then
error( 'Argument 1 to ifSection is required.' )
end
local headings = headingList( title )
local foundSection = false
for i, v in ipairs( headings ) do
if heading == v then
foundSection = true
break
end
end
if foundSection then
return frame.args[2] or ''
else
return frame.args[3] or ''
end
end
--[[
Produces an Alphabet Table of Contents, with links to lettered sections
if they exist on the page, otherwise the letters are not linked.
Usage: {{#invoke:parent|alphabetTOC}}
]]
function p.alphabetTOC( frame )
local headings = headingList( mw.title.getCurrentTitle() )
local ltrs = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }
local wikitext = '{| border=0 cellpadding=4 class="plainlinks" id="alphabetTOC_table" style="font-size:2em;margin:auto;background:#f0f0f0;text-align:center"\n'
local first = true
for i, l in ipairs( ltrs ) do
local found = false
for j, h in ipairs( headings ) do
if l == h then
found = true
break
end
end
if l == 'N' then
-- start a new row for N-Z
wikitext = wikitext .. "\n|-\n"
first = true
end
if first then
wikitext = wikitext .. "|"
first = false
else
wikitext = wikitext .. "||"
end
if found then
wikitext = wikitext .. string.format( '[[#%s|%s]]', l, l )
else
wikitext = wikitext .. l
end
end
return wikitext .. "\n|}"
end
return p