模块:GetParentSec
跳到导航
跳到搜索
此模块的文档可以在模块:GetParentSec/doc创建
local p = {}
function p.getParentSection(frame)
-- 获取当前页面标题
local currentTitle = mw.title.getCurrentTitle()
-- 获取页面内容
local content = currentTitle:getContent()
if not content then return "警告 - 无法获取页面内容!" end
-- 解析章节结构
local sections = {}
for level, section in content:gmatch('(=+)([^=]+)=+') do
table.insert(sections, {
name = mw.text.trim(section), -- 去除前后空白
level = #level
})
end
-- 获取章节名称
local currentSection = frame:getParent().args[1] or ""
-- 查找章节位置
local currentIndex = 0
for i, sec in ipairs(sections) do
if sec.name == currentSection then
currentIndex = i
break
end
end
-- 如果找不到章节,从解析树获取
if currentIndex == 0 then
return "警告- 无法确定当前章节位置!"
end
-- 向上查找最近的更高一级章节
local parentSection = "警告 - 无上级章节!"
for i = currentIndex - 1, 1, -1 do
if sections[i].level < sections[currentIndex].level then
parentSection = sections[i].name
break
end
end
return parentSection
end
return p