| 第2行: |
第2行: |
| | | | |
| | function p.getParentSection(frame) | | function p.getParentSection(frame) |
| | + | -- 获取调用位置的行号 |
| | + | local callLine = frame:getParent():getTitle() |
| | + | |
| | -- 获取当前页面内容 | | -- 获取当前页面内容 |
| | local currentTitle = mw.title.getCurrentTitle() | | local currentTitle = mw.title.getCurrentTitle() |
| 第7行: |
第10行: |
| | | | |
| | -- 解析章节结构 | | -- 解析章节结构 |
| − | local parentStack = {} -- 用于维护父章节层级 | + | local parentStack = {} |
| − | local result = nil | + | local lineNumber = 0 |
| | | | |
| | for line in content:gmatch("[^\r\n]+") do | | for line in content:gmatch("[^\r\n]+") do |
| | + | lineNumber = lineNumber + 1 |
| | + | |
| | -- 匹配章节标题 | | -- 匹配章节标题 |
| | local level, title = line:match("^(=+)([^=]+)=+$") | | local level, title = line:match("^(=+)([^=]+)=+$") |
| | if level then | | if level then |
| − | level = #level -- 计算标题级别 | + | level = #level |
| − | title = mw.text.trim(title) -- 去除前后空格 | + | title = mw.text.trim(title) |
| − |
| |
| − | -- 检查是否包含我们的模板
| |
| − | if title:find("{{GetParentSec}}") then
| |
| − | -- 找到模板调用,获取最近的父章节
| |
| − | if #parentStack > 0 then
| |
| − | result = parentStack[#parentStack].title
| |
| − | else
| |
| − | result = "" -- 没有父章节
| |
| − | end
| |
| − | end
| |
| | | | |
| | -- 维护父章节栈 | | -- 维护父章节栈 |
| 第31行: |
第26行: |
| | table.remove(parentStack) | | table.remove(parentStack) |
| | end | | end |
| − | table.insert(parentStack, {level = level, title = title}) | + | table.insert(parentStack, {level = level, title = title, line = lineNumber}) |
| | + | |
| | + | -- 检查是否是当前调用行 |
| | + | if tostring(lineNumber) == callLine then |
| | + | if #parentStack > 1 then -- 有父章节 |
| | + | return parentStack[#parentStack-1].title |
| | + | else |
| | + | return "" -- 没有父章节 |
| | + | end |
| | + | end |
| | end | | end |
| | end | | end |
| | | | |
| − | return result or "" | + | return "" |
| | end | | end |
| | | | |
| | return p | | return p |