Module:TOC flatlist
Jump to navigation
Jump to search
Outputs a current page's level 2 TOC headers within a flatlist. Used in {{HundredByTenTOC}}.
Usage
{{#invoke:TOC flatlist|flatHeaderList}}
local p = {}
-- Normalize header text to visible text + correct anchor
local function normalizeHeader(header)
-- [[A|B]] → B
header = header:gsub('%[%[[^%]|]+|([^%]]+)%]%]', '%1')
-- [[A]] → A
header = header:gsub('%[%[([^%]]+)%]%]', '%1')
-- Strip basic formatting
header = header:gsub("''+", '')
-- Trim whitespace
header = mw.text.trim(header)
-- Generate MediaWiki-compatible anchor
local anchor = mw.uri.anchorEncode(header)
return anchor, header
end
function p.flatHeaderList(frame)
local title = mw.title.getCurrentTitle()
if not title then
return ''
end
local content = title:getContent()
if not content then
return ''
end
local items = {}
local first = true
-- Match EXACTLY level-2 headers only
for header in content:gmatch('\n==%s*([^=\n][^=\n]-)%s*==%s*\n') do
local anchor, label = normalizeHeader(header)
if label ~= '' then
local link = string.format('[[#%s|%s]]', anchor, label)
if first then
link = "''Contents:'' " .. link
first = false
end
table.insert(items, '* ' .. link)
end
end
if #items == 0 then
return ''
end
return frame:expandTemplate{
title = 'flatlist',
args = {
style = 'font-weight:bold',
[1] = table.concat(items, '\n')
}
}
end
return p