| 第2行: |
第2行: |
| | | | |
| | function p.getParentSection(frame) | | function p.getParentSection(frame) |
| − | local title = frame:getTitle() | + | -- 获取当前页面标题 |
| − | local content = frame:callParserFunction{ | + | local currentTitle = mw.title.getCurrentTitle() |
| − | name = '#tag',
| |
| − | args = { 'pre', frame:expandTemplate{ title = ':' .. title } }
| |
| − | }
| |
| | | | |
| | + | -- 获取页面内容 |
| | + | local content = currentTitle:getContent() |
| | + | if not content then return "警告 - 无法获取页面内容!" end |
| | + | |
| | + | -- 解析章节结构 |
| | local sections = {} | | local sections = {} |
| | for level, section in content:gmatch('(=+)([^=]+)=+') do | | for level, section in content:gmatch('(=+)([^=]+)=+') do |
| | table.insert(sections, { | | table.insert(sections, { |
| − | name = section:match('^%s*(.-)%s*$'), | + | name = mw.text.trim(section), -- 去除前后空白 |
| − | level = #level | + | level = #level |
| | }) | | }) |
| | end | | end |
| | | | |
| − | local currentTitle = mw.title.getCurrentTitle() | + | -- 获取章节名称 |
| | local currentSection = frame:getParent().args[1] or "" | | local currentSection = frame:getParent().args[1] or "" |
| | | | |
| | + | -- 查找章节位置 |
| | local currentIndex = 0 | | local currentIndex = 0 |
| | for i, sec in ipairs(sections) do | | for i, sec in ipairs(sections) do |
| 第27行: |
第30行: |
| | end | | end |
| | | | |
| | + | -- 如果找不到章节,从解析树获取 |
| | if currentIndex == 0 then | | if currentIndex == 0 then |
| − | return "警告 - 无法确定当前章节!" | + | return "警告- 无法确定当前章节 位置 !" |
| | end | | end |
| | | | |
| | + | -- 向上查找最近的更高一级章节 |
| | local parentSection = "警告 - 无上级章节!" | | local parentSection = "警告 - 无上级章节!" |
| | for i = currentIndex - 1, 1, -1 do | | for i = currentIndex - 1, 1, -1 do |