| 第2行: |
第2行: |
| | | | |
| | function p.getParentSection(frame) | | function p.getParentSection(frame) |
| − | -- 获取当前页面 标题 | + | -- 获取当前页面 原始内容 |
| | local currentTitle = mw.title.getCurrentTitle() | | local currentTitle = mw.title.getCurrentTitle() |
| | + | local content = currentTitle:getContent() or "" |
| | | | |
| − | -- 获取页面内容 | + | -- 解析章节结构 |
| − | local content = currentTitle:getContent() | + | local stack = {} -- 用于跟踪章节层级 |
| − | if not content then return "警告 - 无法获取页面内容!" end | + | local found = false |
| | | | |
| − | -- 解析章节结构 | + | for line in content:gmatch("[^\r\n]+") do |
| − | local sections = {}
| + | local level, name = line:match("^(=+)([^=]+)=+$") |
| − | for level, section in content:gmatch('(=+)([^=]+)=+') do
| + | if level then |
| − | table.insert(sections, { | |
| − | name = mw.text.trim(section), -- 去除前后空白
| |
| | level = #level | | level = #level |
| − | })
| + | name = mw.text.trim(name) |
| − | end
| + | |
| − |
| + | -- 检查是否包含我们的模板 |
| − | -- 获取 章节 名称
| + | if name:find("{{ParentSection}}") then |
| − | local currentSection = frame:getParent().args[1] or ""
| + | -- 返回栈顶的父 章节 (如果有) |
| − |
| + | found = true |
| − | -- 查找 章节 位置
| + | break |
| − | local currentIndex = 0
| + | end |
| − | for i, sec in ipairs(sections) do
| + | |
| − | if sec.name == currentSection then
| + | -- 维护 章节 栈 |
| − | currentIndex = i
| + | while #stack > 0 and stack[#stack].level >= level do |
| − | break
| + | table.remove(stack) |
| | + | end |
| | + | table.insert(stack, {level = level, name = name}) |
| | end | | end |
| | end | | end |
| | | | |
| − | -- 如果找不到章节,从解析树获取
| + | if found and #stack > 0 then |
| − | if currentIndex == 0 then | + | return stack[#stack].name |
| − | return " 警告- 无法确定当前章节位置!" | + | else |
| | + | return "" -- 返回空字符串避免破坏标题格式 |
| | end | | 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 | | end |
| | | | |
| | return p | | return p |